简体   繁体   中英

How to use where clause in Query with LEFT JOIN?

how to write my sql query correct? I would like to use WHERE clause in query, but I don't know how is correct. This is my query with mistake:

**SELECT pil.[Buy-from Vendor No_],  pil.No_, pil.Amount, pil.Quantity 
FROM dbo.[„blk“ 2011$Purch_ Inv_ Line]AS pil
WHERE pil.Type=5
LEFT JOIN dbo.[„blk“ 2011$Purch_ Inv_ Header] AS pih
ON pil.[Document No_]=pih.No_
ORDER BY pil.amount**

Move the WHERE clause right before ORDER BY .

Here is the documentation that defines how SELECT statements should look like: http://msdn.microsoft.com/en-us/library/ms189499.aspx .

This is way you have handle left joins

SELECT 
    pil.[Buy-from Vendor No_] 
  ,  pil.No_, pil.Amount
  , pil.Quantity 
FROM dbo.[UAB „Arvi cukrus“ 2011$Purch_ Inv_ Line] pil
LEFT JOIN dbo.[„blk“ 2011$Purch_ Inv_ Header] Pih ON pil.[Document No_]=pih.No_
WHERE pil.Type=5
ORDER BY pil.amount

Where comes after the From clause. The correct query is

   SELECT pil.[Buy-from Vendor No_],  pil.No_, pil.Amount, pil.Quantity 
    FROM dbo.[„blk“ 2011$Purch_ Inv_ Line]AS pil
    LEFT JOIN dbo.[„blk“ 2011$Purch_ Inv_ Header] AS pih
    ON pil.[Document No_]=pih.No_
    WHERE pil.Type=5
    ORDER BY pil.amount;

Put the where after all the joins:

SELECT pil.[Buy-from Vendor No_],  pil.No_, pil.Amount, pil.Quantity 
FROM dbo.[„blk“ 2011$Purch_ Inv_ Line]AS pil
LEFT JOIN dbo.[„blk“ 2011$Purch_ Inv_ Header] AS pih
ON pil.[Document No_]=pih.No_
WHERE pil.Type=5
ORDER BY pil.amoun

WHERE放在ORDER BY之前

Move the WHERE clause after the FROM clause and other table references like so:

SELECT 
  pil.[Buy-from Vendor No_], 
  pil.No_, 
  pil.Amount, 
  pil.Quantity 
FROM ...
...
WHERE pil.Type=5
ORDER BY pil.amount

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM