I find it really hard to explain what is going on, I'll try my best.
We need to make a really simple browser with really simple Favorites + History capabilities, and to do that we need to import them both in a DataSet and use them from there.
The knowledge that I have should be enough, but I would really like to do it more efficient en cleaner. In the database I have 3 tables, one for users, one for favorites and one for history, this is linked with FK's etc. I want a query that returns me every Fav + History url that a user has saved. This is what I have now:
SELECT u_id, u_user, h_url, f_url FROM Users, Favorites, HistoryWHERE u_id = h_id AND u_id = f_id AND u_id = 1
This isn't the result I'm looking for, I want to fill 2 comboboxes, one with favorites and one with history that both are from the person that is logged in at that moment.
I know this should work with join but inner and outer both give to little or to many results, and left and right join don't seem to work for me either, but I cant explain why. :p I'm semi-new to joins btw.
It sounds like you actually want two simple queries, one for favorites and one for history. Both queries just need to have a where clause limiting the user for whom the results are returned.
SELECT f.url
FROM Favorites f
WHERE f.userID = 1
SELECT h.url
FROM History h
WHERE h.userID = 1
If you want to populate two comboboxes, I would suggest that you retrieve two separate lists, one for each combobox. Then you can bind each list separately to its combobox.
While DataSets may not be the best choice, I think they will work for you in this situation. Your objective will be to write two SQL statements, one for each list. Then, you put the query results into DataTables which are contained in one DataSet. A DataTable can be boung to a combobox.
Related
I am having difficulty trying to use LINQ to query a sql database in such a way to group all objects (b) in one table associated with an object (a) in another table into an anonymous type with both (a) and a list of (b)s. Essentially, I have a database with a table of offers, and another table with histories of actions taken related to those offers. What I'd like to be able to do is group them in such a way that I have a list of an anonymous type that contains every offer, and a list of every action taken on that offer, so the signature would be:
List<'a>
where 'a is new { Offer offer, List<OfferHistories> offerHistories}
Here is what I tried initially, which obviously will not work
var query = (from offer in context.Offers
join offerHistory in context.OffersHistories on offer.TransactionId equals offerHistory.TransactionId
group offerHistory by offerHistory.TransactionId into offerHistories
select { offer, offerHistories.ToList() }).ToList();
Normally I wouldn't come to SE with this little information but I have tried many different ways and am at a loss for how to proceed.
Please try to avoid .ToList() calls, only do if really necessary. I have an important question: Do you really need all columns of OffersHistories? Because it is very expensive grouping a full object, try only grouping the necessary columns instead. If you really need all offerHistories for one offer then I'm suggesting to write a sub select (this is also cost more performance):
var query = (from offer in context.Offers
select new { offer, offerHistories = (from offerHistory in context.OffersHistories
where offerHistory.TransactionId == offer.TransactionId
select offerHistory) });
P.s.: it's a good idea to create indexes for foreign key columns, columns that are used in where and group by statements, those are going to make the query faster,
I am making an application that will get information from the exchange server and put it in a list. the list i want is made by 2 commands and give me 2 lists aswell. what i am looking for is an efficient way to putting these 2 lists together.
List one has the following objects
string Name
string alias
string email
List two has the folowing ones
string alias
decimal itemcount
double size
What would be the best way of making these 2 lists one? I want to display it in one Dataview.
Also if possible please include Examples/References. im still pretty new to this all.
I assume that you want one entry for each user, where the alias field is the key to join in. In that case, the easiest is to use LINQ:
var newList = (from a in list1
join b in list2
on a.alias equals b.alias
select new
{
a.Alias,
a.Name,
a.Email,
b.ItemCount,
b.Size
}).ToList();
It will solve the problem. Unless you have extremely high volumes of data and responsiveness demands it will be efficient enough.
This question can actually be applied to any language.
It is similar to this one, but not quite the same.
I have a website application that will be displaying data from database.
Three DB tables:
tblProfessor(Id,FirstName,LastName)
tblStudent(Id,FirstName,LastName)
tblProfessorStudent(Id,StudentId,ProfessorId)
So we have Students and Professors. Students can be taught by multiple professors and professors can teach multiple students.
Two ways of querying data:
return a join of all three tables, in which case we transfer some
duplicate data.
return three sets for each of the table. I know
multiple sets of data can be returned in one call from my web
application. I'm not clear about mechanics of that call, but I think
it will be just one connection to the DB (in contrast to the similar question mentioned above).
The query in the first case:
select
ProfessoirId = p.Id
,ProfessorFirstName = p.FirstName
,ProfessorLastName = p.LastName
,StudentId = s.Id
,StudentFirstName = s.FirstName
,StudentLastName = s.LastName
from tblProfessorStudent ps
inner join tblProfessor p
on p.id = ps.ProfessorId
inner join tblStudent s
on s.id = ps.StudentId
The duplication that I am talking about is returning first and last names of student and professor per each row - combination of "Student is taught by professor" and "professor teaches students". The duplication results in extra amount of kb that needs to be transferred from DB to the app.
The query in the second case will be as simple as this:
select <columns> from tblProfessor
select <columns> from tblStudent
select <columns> from tblProfessorStudent
How should I approach querying data for my app from the performance perspective?
From a pure performance perspective, there's nothing that beats the SQL Server's ability to join data sets in T-SQL. Especially when we are talking about large data sets.
Its sole purpose in life is to manage data and data sets, and it does that where the source of the data is.
Joining "over the wire"/on the client will introduce a great deal of (network) overhead, redundant data traffic, and there's no or close to no way that fancy client algorithms can overcome this.
Of course, and as usual: YMMV, "it depends" is always applicable to my statement.
If you are concerned about performance, then you should not return all rows from your tables. Once the database grows, this will cause the application to slow down. You should filter your data to get only the rows you need to display to the user. You can also consider implementing paging, so that you don't display a lot of rows at once.
I think that what matters most in this case is how you are using the data. If you have the correct indexes implemented, SQL Server will join the tables just fine, don’t worry about it. I’m pretty sure it will be faster than running 3 selects. You said you are worried about duplicate data, but what sort of duplication? If you join the 3 tables you’ll have the real data, I mean, teachers that teach X students and students that are taught by X teachers. No duplications! So again, it depends on how you are using the result sets. Are you simply displaying a list of students and a list of teachers? In this case go with option 2. If you need to show Teacher A has the following students, then go with the join on option 1 because if you choose option 2, you will have to manipulate the ProfessorStudent data sets (which I assume has only IDs) to get the names from the other 2 datasets and this is too much trouble in my opinion.
I am very new to LINQ to SQL, so please forgive me if its a layman sort of question.
I see at many places that we use "select new" keyword in a query.
For e.g.
var orders = from o in db.Orders select new {
o.OrderID,
o.CustomerID,
o.EmployeeID,
o.ShippedDate
}
Why don't we just remove select new and just use "select o"
var orders = from o in db.Orders select o;
What I can differentiate is performance difference in terms of speed, i.e. then second query will take more time in execution than the first one.
Are there any other "differences" or "better to use" concepts between them ?
With the new keyword they are building an anonymous object with only those four fields. Perhaps Orders has 1000 fields, and they only need 4 fields.
If you are doing it in LINQ-to-SQL or Entity Framework (or other similar ORMs) the SELECT it'll build and send to the SQL Server will only load those 4 fields (note that NHibernate doesn't exactly support projections at the db level. When you load an entity you have to load it completely). Less data transmitted on the network AND there is a small chance that this data is contained in an index (loading data from an index is normally faster than loading from the table, because the table could have 1000 fields while the index could contain EXACTLY those 4 fields).
The operation of selecting only some columns in SQL terminology is called PROJECTION.
A concrete case: let's say you build a file system on top of SQL. The fields are:
filename VARCHAR(100)
data BLOB
Now you want to read the list of the files. A simple SELECT filename FROM files in SQL. It would be useless to load the data for each file while you only need the filename. And remember that the data part could "weight" megabytes, while the filename part is up to 100 characters.
After reading how much "fun" is using new with anonymous objects, remember to read what #pleun has written, and remember: ORMs are like icebergs: 7/8 of their working is hidden below the surface and ready to bite you back.
The answer given is fine, however I would like to add another aspect.
Because, using the select new { }, you disconnect from the datacontext and that makes you loose the change tracking mechanism of Linq-to-Sql.
So for only displaying data, it is fine and will lead to performance increase.
BUT if you want to do updates, it is a no go.
In the select new, we're creating a new anonymous type with only the properties you need. They'll all get the property names and values from the matching Orders. This is helpful when you don't want to pull back all the properties from the source. Some may be large (think varchar(max), binary, or xml datatypes), and we might want to exclude those from our query.
If you were to select o, then you'd be selecting an Order with all its properties and behaviours.
I am using NHibernate in an MVC 2.0 application. Essentially I want to keep track of the number of times each product shows up in a search result. For example, when somebody searches for a widget the product named WidgetA will show up in the first page of the search results. At this point i will increment a field in the database to reflect that it appeared as part of a search result.
While this is straightforward I am concerned that the inserts themselves will greatly slow down the search result. I would like to batch my statements together but it seems that coupling my inserts with my select may be counter productive. Has anyone tried to accomplish this in NHibernate and, if so, are there any standard patterns for completing this kind of operation?
Interesting question!
Here's a possible solution:
var searchResults = session.CreateCriteria<Product>()
//your query parameters here
.List<Product>();
session.CreateQuery(#"update Product set SearchCount = SearchCount + 1
where Id in (:productIds)")
.SetParameterList("productIds", searchResults.Select(p => p.Id).ToList())
.ExecuteUpdate();
Of course you can do the search with Criteria, HQL, SQL, Linq, etc.
The update query is a single round trip for all the objects, so the performance impact should be minimal.