I have this database running (ignore that the ERD below was done in Access, this is being made in Microsoft SQL Server 2005).
What I need to do is if you look at the users table and the orderContents table I need to make a query that:
Collects the users' names and any products they have bought (preferably shown by title not ID) as well as still showing the users that have not ordered any products.
I get the feeling there's a left join involved, but can't quite see how to do it.
SELECT * FROM a LEFT OUTER JOIN b ON a.id = b.id instead of
SELECT * FROM a LEFT JOIN b ON a.id = b.id
generates a different execution plan?
My query is more complex, but when I change "LEFT OUTER JOIN" to "LEFT JOIN" I get a different execution plan, which is absolutely baffling me! Especially considering everything I know and was able to research essentially said the "OUTER" is implied in "LEFT JOIN".
I am stuck in a bit of a mess, and i really don't know how to get out of it.
I am a dot.net developer, working with MS SQL server 2000.
I am trying to write a query which essentially gives the amount of stock available for a particular stock_code.
select Stock_code, description from stock
Now what i want to do is, for each one of the stock_code that apears in the table above i want to look into another table called pop_item, and get the closest delivery_date for that particular stock_code. So i have top 1 and order it by delivery_date desc.
Individually for a particular stock_code, i can do this no problem. And here is my code for stock_code='E0016/6'
select top 1 stock_code, delivery_date, order_number,qty_order-qty_delivered as onorder from pop_item where stock_code='E0016/6' and qty_order>qty_delivered order by delivery_date desc
But I can't seem to be able to do this for all the stock_code, and not a specific one, cause even though i try and left outer join it, i can't access the outer stock_code from the first query into the next...
i.e
select stock.Stock_code, description, tempp.stock_code, tempp.delivery_date, tempp.onorder from stock
left outer join
(select top 1 stock_code, delivery_date, order_number,qty_order-qty_delivered as onorder from pop_item where
--Can't say this(stock_code= stock.stock_code and ) qty_order>qty_delivered order by delivery_date desc) as tempp
on tempp.stock_code=stock.stock_code
Now my question is, is there anyway to access stock.stock_code within the second query? Casue the whole query on top returns only one value for delivery_date, only of the highest delivery date in the whole of pop_item. which make sense... but i don;t know how to get around this...
OOOOOOOOOOOOOOOOOOhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!
Hope someone can help me.
Regards,
Munira
ps- should i be using a cursor, can i call cursors from asp.net. every where i read about cursors they adivice us not to use them.
Here's a little background on the query. I have a list of documents by an id number in one table and the description of the sheets in another table. It's a one to many relationship, so for each description, there may be multiple entries in the documents table that it applies to. For example:
So the query I am using uses a left join to combine the data from the one table into the other. There might not be an entry for the description, so for some Document entries, the description field may be blank. For some reason, certain queries take about 2 minutes longer than others who retreive 5 times the information.
In SQL Manager, is says "Executing Query. Waiting for response from data source." After about 20 seconds it says "Retrieving Data..." then about a minute later, it finally comes up with the data. I can select another parent that has a lot more items and it comes up in about 3 seconds max.
It's running on SQL Server 2005 with 2GB of RAM.
Any suggestions on tracking down the reason for the slowness would be great.
I have been working on this for a little bit and have gotten to this point. Below is the query in blue, the error in red. Now, from what I gather the error is telling me I can't insert a duplicate product code into tblProduct. Isn't that what the left join is exactly not doing, as in, the left join is inserting all records from Complete_records into tblProduct where the code is null(does not exist) in tblProduct? Or, is this an issue where the identity number, productID in tblProduct, isn't starting at the next number in turn?
Thanks.
Set Identity_Insert tblProduct on DECLARE @MaxId int
SELECT @MaxID=MAX(productID) FROM tblProduct
SELECT IDENTITY(int,1,1) AS ID,Complete_products.APNum, Complete_products.Title, Complete_products.CategoryID, Complete_products.Mountable, Complete_products.price, Complete_products.Height, Complete_products.Width, Complete_products.IRank, Complete_products.frameable, Complete_products.Typ INTO #Temp FROM Complete_products LEFT OUTER JOIN tblProduct AS tblProduct_1 ON Complete_products.APNum = tblProduct_1.productCode where tblProduct_1.productCode IS NULL
INSERT INTO tblProduct (productID,productCode, productName, productNavID, CanBeMounted, productRetailPrice, productHeight, productWidth, Rank, CanBeFramed, ProductType) SELECT @MaxID + ID, APNum, Title, CategoryID, Mountable, price, Height, Width, IRank, frameable, Typ FROM #Temp
(236752 row(s) affected) Msg 2601, Level 14, State 1, Line 13 Cannot insert duplicate key row in object 'dbo.tblProduct' with unique index 'IX_tblProductt_productCode'. The statement has been terminated.
I was trying to run the follwoing query.It is giving me error
"select woancestor.wonum,wplabor.laborcode, wplabor.quantity,wplabor.laborhrs from wplabor,workorder left outer join woancestor on workorder.wonum=woancestor.wonum and wplabor left outer join labtrans on wplabor.laborcode=labtrans.laborcode where woancestor.ancestor='572099' and workorder.istask=1 and workorder.wonum=wplabor.wonum"
Error is "Server: Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'left'."
But the following query works fine
"select woancestor.wonum,wplabor.laborcode, wplabor.quantity,wplabor.laborhrs from wplabor,workorder left outer join woancestor on workorder.wonum=woancestor.wonum where woancestor.ancestor='572099' and workorder.istask=1 and workorder.wonum=wplabor.wonum"
I have a SQL database where I am attempting to perform a complicated query that I cannot seem to figure out. I am using SQL Server.
I have 4 tables (TableA, TableB, TableC, and TableD). TableA and TableB are guaranteed to have a relationship.
TableC and TableD are guaranteed to have a relationship.
The trick is, I need to link between TableA and TableC essentially using a LEFT JOIN. I need to retrieve all of the values from TableA regardless and the information from TableC and TableD if there is a link, if there isn't a link, then the values from TableC and TableD need to be empty strings.
Does anyone know how I can do this? I've been trying for the last 5 hours without any luck. I feel I'm close, but there is something I feel I'm overlooking.
I need to convert a OUTER APPLY hint in my query to LEFT JOIN.How it can be done?The code which is presently is this: OUTER APPLY Additional Fields. nodes('/AdditionalFields/AdditionalField') AS AF (C)
I was writing a query using both left outer join and inner join. And the query was ....
SELECT S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname FROM Production.Suppliers AS S LEFT OUTER JOIN (Production.Products AS P INNER JOIN Production.Categories AS C
[code]....
However ,the result that i got was correct.But when i did the same query using the left outer join in both the cases
i.e..
SELECT S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname FROM Production.Suppliers AS S LEFT OUTER JOIN (Production.Products AS P LEFT OUTER JOIN Production.Categories AS C ON C.categoryid = P.categoryid) ON S.supplierid = P.supplierid WHERE S.country = N'Japan';
The result i got was same,i.e
supplier country productid productname unitprice categorynameSupplier QOVFD Japan 9 Product AOZBW 97.00 Meat/PoultrySupplier QOVFD Japan 10 Product YHXGE 31.00 SeafoodSupplier QOVFD Japan 74 Product BKAZJ 10.00 ProduceSupplier QWUSF Japan 13 Product POXFU 6.00 SeafoodSupplier QWUSF Japan 14 Product PWCJB 23.25 ProduceSupplier QWUSF Japan 15 Product KSZOI 15.50 CondimentsSupplier XYZ Japan NULL NULL NULL NULLSupplier XYZ Japan NULL NULL NULL NULL
and this time also i got the same result.My question is that is there any specific reason to use inner join when join the third table and not the left outer join.
OLEDB source 1 SELECT ... ,[MANUAL DCD ID] <-- this column set to sort order = 1 ... FROM [dbo].[XLSDCI] ORDER BY [MANUAL DCD ID] ASC
OLEDB source 2 SELECT ... ,[Bo Tkt Num] <-- this column set to sort order = 1 ... FROM ....[dbo].[FFFenics] ORDER BY [Bo Tkt Num] ASC
These two tasks are followed immediately by a MERGE JOIN
All columns in source1 are ticked, all column in source2 are ticked, join key is shown above. join type is left outer join (source 1 -> source 2)
result of source1 (..dcd column) ... 4-400-8000119 4-400-8000120 4-400-8000121 4-400-8000122 <--row not joining 4-400-8000123 4-400-8000124 ...
result of source2 (..tkt num column) ... 4-400-1000118 4-400-1000119 4-400-1000120 4-400-1000121 4-400-1000122 <--row not joining 4-400-1000123 4-400-1000124 4-400-1000125 ...
All other rows are joining as expected. Why is it failing for this one row?
Why would I use a left join instead of a inner join when the columns entered within the SELECT command determine what is displayed from the query results?
Why does this right join return the same results as using a left (or even a full join)?There are 470 records in Account, and there are 1611 records in Contact. But any join returns 793 records.
select Contact.firstname, Contact.lastname, Account.[Account Name] from Contact right join Account on Contact.[Account Name] = Account.[Account Name] where Contact.[Account Name] = Account.[Account Name]
Hello Experts, Been struggling with this issue all morning and beginning to get a headache. Essentialy my problem is this. I have a gridview control that ive bound to datasource where the select statement is using an inner join to retrieve textual info from one table in refernce to an object_id contained within both. i.e SelectCommand="SELECT 'multiple fields from both tables'FROM ZCRMTAB_ACTIVITY INNER JOIN ZCRMTAB_ACT_LOG ON ZCRMTAB_ACT_LOG.OBJECT_ID = ZCRMTAB_ACTIVITY.OBJECT_ID WHERE (ZCRMTAB_ACTIVITY.REF_CUST_NO = @REF_CUST_NO) ORDER BY ZCRMTAB_ACTIVITY.CREATED_AT DESC"> <SelectParameters><asp:QueryStringParameter Name="fieldName" QueryStringField="value" Type="String" /> My problem is that this returns individual row results and are displayed on individual lines. Where the object_id is the same i want all the textual info to be displayed within the same row. Does anyone know how i can accomplish this? Thanks in advance
I'm trying to join 2 tables. I thought I was getting the correct results but it turns out I'm not. My Query: SELECT IVINVA, IVORDN, IVCSLN, IVRESR, IVCITM, CONVERT(varchar(12),CAST(IVIAMT as money),1) AS ExtPrice, CONVERT(varchar(12),CAST(IVPIVC as money),1) AS DistPrice, IVCSUM, IVQYCS, IVDESC, OIRESR, OIDPCT, CONVERT(varchar(12),CAST(IVPIVC - (OIDPCT / 100 * IVPIVC) as money),1) AS NetPrice FROM INVDET1_TBL LEFT JOIN ORDDIS_TBL ON ORDDIS_TBL.OIORDN = INVDET1_TBL.IVORDN AND ORDDIS_TBL.OIRESR = INVDET1_TBL.IVRESR WHERE IVORDN = '0859919' AND IVINVA = '00324024' Basically, my problem lies in the seonc condition of the LEFT JOIN. I needed to set the two tables equal my item number, because in some situations I need that logic to get the correct result. It most other cases, that item column in the ORDDIS_TBL is NULL, thus giving me the wrong results. In that case, I would want the JOIN to only be ORDDIS_TBL.OIORDN = INVDET1_TBL.IVORDN, and not include the second part. Is there a way I can condition this with an If statement, If ORDDIS_TBL.OIRESR is Null then do this join, if not, then do this? I'm confused how to get the proper result here.
3) select p.komorka,isnull(sum(ustalenia),0) from #plantemp p left join analiza_1 a on p.komorka=a.komorka where a.koniec between '20040701'and '20040731' group by p.komorka
komorka ustalenia (sum)
08.0000 SI/1788138.9300 SI/262856.8900
I need all rows from table 1 bat right and left join gives me the same results, WHY
As you can see the ParentIndexID and ChildIndexID fields refer to tblIndices.IndexID I would like a stored procedure as follows: show all index names and show the wights for the indexID you passed. This is what I have so far and it is not correct yet. Not sure what the syntax should be.
alter PROCEDURE [dbo].[uspBasketIndices_Get]
@IndexIDint
AS
select i.IndexID, i.[Name], bc.Weight from tblIndices as i left join tblBasketConstituents as bc on i.IndexID = bc.ParentIndexID and i.IndexID = @IndexID order by i.[Name]
Any one know any facts and figures about maximum Left Joins allowed (or recommended) in one query?
I am running a MS SQL 2000 my database is full of relational data and most of my foreign keys (INT data type) are a Clustered Indexed, Usually I will only be pulling one record from collection of about a dozen tables, but the Database is expected to grow fast and become big.
Right now I have a Stored Proc that has eight(8) LEFT JOINs in it. My worry is that this query will kill me as the database approaches 50,000 records.
Hi all. My query works fine, it generates reports but not my expected result.
select d.fullname, p.nickname, p.birthdate, p.birthplace, p.gender, p.civilstatus, p.religion, p.nationality, p. weight, p.height, p.haircolor, p.eyecolor, p.complexion, p.bodybuilt, p.picture, p.dialectspoken, d.mobilephone, d.prprovince,[Age] = dbo.F_AGE_IN_YEARS( birthdate, getdate() ), c.name, c.address, c.telno, c.email, c.occupation, ed.year1, ed.year2, ed.degree, sch.schname from hremployees as e inner join psdatacenter as d on e.empdcno = d.dcno inner join pspersonaldata as p on e.empdcno = p.dcno left join hrappempcharrefs as c on e.empdcno = c.empdcno left join hrappempeducs as ed on e.empdcno = ed.empdcno left join hrsetschools as sch on ed.schoolcode = sch.schcode
the above query gives a 77 records
if i ran "select * from hremployees" generates 60 records
i think the error is in the left joining. hrappempcharrefs, hrappempeducs and hrsetschools must be left joined to hremployees.
Hi Guys, I started working with linq and vb9.0 but i have a small problem i could feagure how to solve in c# but not in vb I wanted to make left join or right join on vb 9.0 and linq is it possible or this is only c# feature ? Waiting to hear from u guys, Thanks Softy
Hello! I need to write a query using left outer join and I'm having trouble with it. I have 2 tables:customer and cust_info. I want to pull all records from customer table and cust_info table even if there is no related data in cust_info table. But I need one condition in this query:only records from customer table where cus_type in ("A","B","C"). I don't need all other types ("D","E").
So my query looks like this:
select customer.cus_name,customer.cus_address,customer.cu s_type,cus_info.status from customer left outer join cus_info ON customer.sxdat_pk = cus_info.sxdat_pk and cus_type in ("A","B","C") AND cus_info.cus_table = 'CUSTOMER'
The result should be like this:
cus_name cus_address cus_type status Amoco 457 bent A new Bingo 47 lone oak C NULL Sears 1020 Magic dr. B exist
But my query pulls records for customers with type "D" and "E" that I'm trying to exclude from result.
I have to left join 2 tables. The first consists of columns:id, description, descr_num. The second table: id, descr_num, value.
I need to extract description from table1 where descr_num is in the range , say, 1-10.
LEFT JOIN
extract value from table2 ,descr_num should be in the same range. in table2 some values from (1,10) and desc_num could be not present. BUT i want this left join to be limited as i said.
Is there any solution to this prob. without creating temp tables. Or actually can i do such a join? Thank you
To join the table but MUST follow the condition as bitActiv = TRUE: select emp.nvcEmpName, emp.nvcEmpAddress, ety. nvcEmployeeType from cst_EmpProfile emp left join cst_EmpType on emp.intEmployeeTypee = ety.intEmpType and emp.bitActiv = 1.
But, the sql statement doesnt output the my expected result. Because the data row return must be 1st and 2nd row as it bitActiv = true. So, how's I going achieve what i want. tq.
Hi, I'm getting the error Syntax error (missing operator) in query expression 'dbPWork.id = dbPWorkWord.work_id LEFT JOIN words ON dbPWorkWord.word_id = words.id'." on the query below. Everything looks in place to me. Do you see anything that shouldn't work?
Query:
Code:
Code:
SELECT DISTINCT dbPWork.id, description_e as description, w_id , dateStart, dateEnd FROM dbPWork LEFT JOIN dbPWorkW ON dbWork.id = dbPWorkW.work_id LEFT JOIN words ON dbPWorkW.word_id = words.id
Everything works fine until I add the second LEFT JOIN statement. Any ideas? I'm stumped.
Hi, Iwant to make a left join between two tables connected with a specific field but I also want to have some criteria on the right table. I want to display all the rows from the first(left) table and only the rows from the secod (right) table that match the join and the criteria. However If I have criteria on the second table the join behaves like an inner join displaying only the rows that exist in both tables. In MS Access instead of the right table I use a query in which I enter the criteria and then I connect it with a left join in a new query in order to get the right results. How can I do itin MSSQLServer without using Views? Must I use a subquery with Exists and what is the right syntax in order to achieve this?
a job can be done with 1 or more operators I want to be able to show user both assigned and unassigned operator on the front end on a certain job so I haev only parm being passed in @jobID.
How do I got about showing all the operators but somehow differentiate ones already assigned to job