Two inner joins in one SQL query string - c#

I'm currently trying to get information from three tables. I have a 'worker' table which includes a store ID (store_idStore) and a job ID (job_idJob) as foreign keys. In the Store and Job tables, each of them has a 'Name' field - this is the data I want to return in my query along with all of the information from Worker. My only caveat is that I have to put the query into a string in C#.
So far I'm able to join and get the information from Worker and Store:
SELECT worker.*, store.Name AS 'Store'
from worker inner join store on worker.Store_idStore = store.idStore
How do I expand this to get the relative Job's name as well?

Try this One :
SELECT worker.*,store.Name AS store,job.Name AS job from worker inner join store on worker.Store_idStore = store.idStore and worker inner join job on worker.job_idJob = job.idJob

Just append another inner join on the end
SELECT w.*,s.Name AS 'Store', j.name as 'job' from worker w
inner join store s on worker.Store_idStore = store.idStore
Inner join job J on worker.job_idjob = job.idjob

Try this:
SELECT DISTINCT w.*, s.*, j.*
FROM worker AS w
LEFT JOIN store AS s ON w.store_idStore = s.id
LEFT JOIN job AS j ON w.job_idJob = j.id
Of course you can replace * with any columns' names you want. And you can add Where clause at the end.

Related

How to join tables and queries in C# with access database

this is how i join 2 tables and select form it:
OleDbDataAdapter DataA = new OleDbDataAdapter(#"Select tfr.FeedID, tf.FeedName, tfr.FeedQuantity, tf.DM
FROM tFeeds AS tf
INNER JOIN tFeedsRations AS tfr ON (tf.FeedID=tfr.FeedID)", Connection);
but what about adding a access query to this select command?
for example I want to add this statement to my select command:
Select qfq.FeedDMQuantites
From qFeeds_Quantities as qfq
what should I do?
Well add another JOIN condition to this table qFeeds_Quantities (assuming you have a relationship to this table or a common column among other table).
Assuming you have a common column like FeedID in this new table as well you can make another JOIN like
select tfr.FeedID, tf.FeedName, tfr.FeedQuantity,
tf.DM, qfq.FeedDMQuantites
FROM (tFeeds AS tf
INNER JOIN tFeedsRations AS tfr ON tf.FeedID = tfr.FeedID)
INNER JOIN qFeeds_Quantities as qfq ON tf.FeedID = qfq.FeedID;
If you want to include another JOIN then parenthesize like
FROM ((tFeeds AS tf
INNER JOIN tFeedsRations AS tfr ON tf.FeedID = tfr.FeedID)
INNER JOIN qFeeds_Quantities as qfq ON tf.FeedID = qfq.FeedID)
INNER JOIN BLAH AS bll ON bll.test = tf.test;

MS Access Database SQL Query

I have 3 Tables called Invoice, Customer and Company. I want to merge this 3 tables into single using Query. In Invoice Table contain Customer Id and Company Id. How to Join 3 tables ?
I tried Invoice and Customer Table working fine with this query. But I dont have idea to add 3rd table with this.
SELECT RPT_Invoice_Less.InvoiceNumber, RPT_Invoice_Less.Terms,
RPT_Invoice_Less.Invoicedate, RPT_Invoice_Less.OurQuote,
RPT_Invoice_Less.SalesPerson, RPT_Customer.CustomerName,
RPT_Customer.CustomerId, RPT_Customer.ContactPerson,
RPT_Customer.BillingAddress, RPT_Customer.DeliveryAddress,
RPT_Invoice_Less.OrderNumber, RPT_Invoice_Less.ShippingBy,
RPT_Invoice_Less.ShipReferenceNo, RPT_Invoice_Less.Notes,
RPT_Invoice_Less.Price, RPT_Invoice_Less.Discount,
RPT_Invoice_Less.Shipping, RPT_Invoice_Less.Tax,
RPT_Invoice_Less.GrandTotal, RPT_Invoice_Less.Company
FROM RPT_Invoice_Less
INNER JOIN RPT_Customer
ON RPT_Invoice_Less.CustomerId = RPT_Customer.CustomerId;
this code working fine for 2 tables
SELECT RPT_Invoice_Less.InvoiceNumber, RPT_Invoice_Less.Terms, RPT_Invoice_Less.Invoicedate, RPT_Invoice_Less.OurQuote, RPT_Invoice_Less.SalesPerson, RPT_Customer.CustomerName, RPT_Customer.CustomerId, RPT_Customer.ContactPerson, RPT_Customer.BillingAddress, RPT_Customer.DeliveryAddress, RPT_Invoice_Less.OrderNumber, RPT_Invoice_Less.ShippingBy, RPT_Invoice_Less.ShipReferenceNo, RPT_Invoice_Less.Notes, RPT_Invoice_Less.Price, RPT_Invoice_Less.Discount, RPT_Invoice_Less.Shipping, RPT_Invoice_Less.Tax, RPT_Invoice_Less.GrandTotal, RPT_OrionSystem.Company, RPT_OrionSystem.CompanyId
FROM RPT_Invoice_Less
INNER JOIN RPT_Customer
ON RPT_Invoice_Less.CustomerId = RPT_Customer.CustomerId
INNER JOIN RPT_OrionSystem
ON RPT_Invoice_Less.CompanyId = RPT_OrionSystem.CompanyId;
This code showing syntax error.
Help me to add 3rd Company table to this.
Supposing that you have a CompanyID field (or something like that) in the RPT_Customer table or in the RPT_Invoice_Less, it is just a matter to add another INNER JOIN
....
FROM ((RPT_Invoice_Less
INNER JOIN RPT_Customer
ON RPT_Invoice_Less.CustomerId = RPT_Customer.CustomerId)
INNER JOIN RPT_OrionSystem
ON RPT_Invoice_Less.CompanyID = RPT_OrionSystem.CompanyID)

Reduce Execution Time in MYSQL from ASP.NET

i have a table which is relevant GPS application in mysql. whenever i am executing from asp.net application it showing fetal error. so i have decided to run in mysql, it will take more than 1 min(exactly 70 sec) for executing the SP. is it possible to sort out the issues.
Further information:
table 1 : server_gpsdata(it contains gps data. it locks every 10 secs from gps device).
select * from server_gpsdata SD
INNER JOIN mstcab MC on MC.cabid= SD.cabid
INNER JOIN server_tblstatus TS on TS.statusid= MC.CabStatusid
INNER JOIN carmaster CM on CM.carid= MC.carid
INNER JOIN cabtype CT on CT.cabtypeid= CM.sizeid
where date(SD.cur_datetime) =current_date and
MC.Cabid not in (select D.cabid from trncabdriver D
where date(D.logintime)=current_date) and
SD.gpsdataid in (select max(SGD.gpsdataid) from server_gpsdata SGD
where date(SGD.cur_datetime)=current_date
group by SGD.cabid);
The following should show a significant improvement in performance:
select SD.*, MC.*, TS.*, CM.*, CT.* from
(select max(SGD.gpsdataid) maxgpsdataid from server_gpsdata SGD
where date(SGD.cur_datetime)=current_date
group by SGD.cabid) SDM
INNER JOIN server_gpsdata SD ON SDM.maxgpsdataid = SD.gpsdataid
INNER JOIN mstcab MC on MC.cabid= SD.cabid
INNER JOIN server_tblstatus TS on TS.statusid= MC.CabStatusid
INNER JOIN carmaster CM on CM.carid= MC.carid
INNER JOIN cabtype CT on CT.cabtypeid= CM.sizeid
LEFT JOIN trncabdriver D ON MC.Cabid= D.Cabid AND date(D.logintime)=current_date
where D.Cabid IS NULL
Note that both the existing and proposed queries are returning all columns from the server_gpsdata, mstcab, server_tblstatus, carmaster and cabtype tables - the query is likely to perform better if only the columns that are actually required are selected in the query.

How do I use multiple IDs from a table with an INNER JOIN using SQL?

I have a list of SiteUsers in one table and another table has columns with different types of owners (ID) for the record. For example, the SiteUserID in the SiteUsers table will be used for the SalesRepID, the StaffingManagerID, and RecruiterID in the Fill table. Of course, the SiteUserID is different for each of the values in the Fill table.
I'd like to return the name of the SiteUser for each ID column in the Fill Table.
How do I properly construct a JOIN statement to do this?
I'm guessing this is done through INNER JOIN, but I'm not sure.
My current select statement already has an INNER JOIN as I'm pulling the name of the FillType from another table. I'm using this in an asp.net application.
I'm not sure if this is even possible. Any help is appreciated.
Since each of the IDs in the Fills table allows null, you probably want to LEFT JOIN to the SiteUsers table like so:
SELECT f.FillID, s1.SiteUserLastName 'SalesRep', s2.SiteUserLastName 'StaffingManager', s3.SiteUserLastName 'Recruiter'
FROM Fills f
LEFT JOIN SiteUsers s1 on f.SalesRepID = s1.SiteUserID
LEFT JOIN SiteUsers s2 on f.StaffingManagerID = s2.SiteUserID
LEFT JOIN SiteUsers s3 on f.RecruiterID = s3.SiteUserID
You can always UNPIVOT the results like so:
SELECT
DISTINCT
unpvt.FillID
,unpvt.RepID
,unpvt.RepType
,s.SiteUserFirstName
,s.SiteUserLastName
FROM
(SELECT
FillID
,SalesRepID
,StaffingManagerID
,RecruiterID
FROM Fills
) f
UNPIVOT
(RepID FOR RepType IN
(SalesRepID, StaffingManagerID,RecruiterID)
) AS unpvt
JOIN SiteUsers AS s on unpvt.RepID = s.SiteUserID`
Obviously you can play with exact output (such as substituting the RepType for a different value with a CASE statement or whatnot.
My question is: why the piss-poor design? Instead of having three IDs in the Fills table, you should have a junction table between SiteUsers and Fills to allow many-to-many relationships. IF it were designed with a junction table, you'd never have had to ask this question.
You will have to join the Fill table with the SiteUsers table multiple times, one for each xxxID column in the Fills for which you want the SiteUser name and combine the results using an union as below:
select a.SiteUserId, a.SiteUserFirstName, a.SiteUserLastName
from dbo.SiteUsers a
inner join dbo.Fills b on b.SalesRepId = a.SiteUserId
UNION
select a.SiteUserId, a.SiteUserFirstName, a.SiteUserLastName
from dbo.SiteUsers a
inner join dbo.Fills b on b.StaffingManagerId = a.SiteUserId
UNION
select a.SiteUserId, a.SiteUserFirstName, a.SiteUserLastName
from dbo.SiteUsers a
inner join dbo.Fills b on b.RecruiterId = a.SiteUserId

LINQ2SQL - More Questions on when a Cross join with where clause is emitted instead of Inner Join

This is a two part question and for education purposes rather than trying to find a solution to a problem.
I've seen this already and realize that it's very similar to my question
LINQ2SQL - Cross join emitted when I want inner join
But I am hoping for more information from you LINQ and SQL gurus as to why the cross join is created instead of inner join in LINQ2SQL. Additionally, can someone explain how SQL Server decides on the execution plan (or link to further information) since both of these queries generate the same plan? From what I understand, this means that the performance of the queries are the same.
I've created a small example that runs two LINQ expressions on my database that generates these two different SQL queries.
For those who don't want to bother, here's my example db diagram:
http://dl.dropbox.com/u/13256/Screen%20shot%202011-03-16%20at%2011.41.56%20AM.png
Here are the two queries:
Cross Join with Where Clause
var q = from item in context.Items
join i_mem in context.Memberships on new { item_id = item.ID, user_id =
current_user_id.Value } equals new { item_id = i_mem.RelatedItemID, user_id =
i_mem.RelatedUserID } into sq_i_m
from im in sq_i_m.DefaultIfEmpty()
join i_cat in context.Categories on item.RelatedCategoryID equals i_cat.ID
into sq_i_cat
from proj in sq_i_cat
select item;
Inner Join
from item in context.Items
join i_mem in context.Memberships on
new { item_id = item.ID, user_id = current_user_id.Value }
equals
new { item_id = i_mem.RelatedItemID, user_id = i_mem.RelatedUserID }
into sq_i_m
from im in sq_i_m.DefaultIfEmpty()
join i_cat in context.Categories on item.RelatedCategoryID equals i_cat.ID
select item
And here is the test program if you'd like to see for yourself.
Thanks for everyone's help.
Mustafa
They are the same thing, so it does not matter which LINQ2SQL emits.
An inner join is logically equivalent to a cross join with a where clause filter equivalent to the on of the inner join clause.
That's why Sql Server generates the same query plan.
To be clear, the inner join:
Select f1
From T1 inner join T2 on T1.k = T2.k
where T1.f2 like 'X%'
Is the same as the cross join:
Select f1
From T1 cross join T2
where T1.k = T2.k
and T1.f2 like 'X%'
is the same as old-style SQL:
Select f1
From T1, T2
where T1.k = T2.k
and T1.f2 like 'X%'
Lets say you have a datacontext called MyDataContext.
using(MyDataContext db = new MyDataContext())
{
var q = db.Items.Where(x=> x.Categories.Name == "myCategory").Select(x=> x);
}
This is a very simple example, but you didn't need to write out a join or a subquery in TSQL syntax. (I hate writing TSQL).

Categories