简体   繁体   English

使用LEFT JOIN返回不匹配的行

[英]Using LEFT JOIN to returns rows that don't have a match

I have a situation where we have a table that contains all the items, if the item was sold it has an entry in another table. 我有一种情况,我们有一个包含所有项目的表,如果该项目已售出,则它在另一个表中有一个条目。

I am trying to get all the items returned that have not been sold, but it doesn't seem to work. 我试图让那些尚未售出返回的所有项目,但它似乎并没有工作。

I have this SQL: 我有这个SQL:

SELECT a.auction_id FROM auctions AS a 
LEFT JOIN winners AS w ON a.auction_id=w.auction_id AND w.winner_id IS NULL
WHERE a.owner_id=1234567 AND a.is_draft=0 AND a.creation_in_progress=0;

I thought this would only return items from the auctions table that don't have a matched entry in the winners table since I am doing AND w.winner_id IS NULL . 我以为这只会从auctions表中返回在winners表中没有匹配条目的项目,因为我正在执行AND w.winner_id IS NULL

However it seems to still return the same amount of rows as it does when I leave off AND w.winner_id IS NULL . 但是,它似乎仍然返回与我离开AND w.winner_id IS NULL时相同的行数。

SELECT a.auction_id
  FROM auctions AS a
  LEFT JOIN winners AS w
    ON a.auction_id = w.auction_id
 WHERE a.owner_id = 1234567
   AND a.is_draft = 0
   AND a.creation_in_progress = 0
   AND w.winner_id IS NULL

This belongs in the WHERE clause: 这属于WHERE子句:

   AND w.winner_id IS NULL

Criteria on the outer joined table belongs in the ON clause when you want to ALLOW nulls. 当您要允许空值时,外部联接表上的条件属于ON子句。 In this case, where you're filtering in on nulls, you put that criteria into the WHERE clause. 在这种情况下,如果您要过滤null,则将该条件放入WHERE子句中。 Everything in the ON clause is designed to allow nulls. ON子句中的所有内容旨在允许空值。

Here are some examples using data from a question I answered not long ago: 以下是一些使用我不久前回答的问题中的数据的示例:

Proper use of where x is null: http://sqlfiddle.com/#!2/8936b5/2/0 正确使用x为null的地方: http : //sqlfiddle.com/#!2/8936b5/2/0

Same thing but improperly placing that criteria into the ON clause: http://sqlfiddle.com/#!2/8936b5/3/0 同样的事情,但是不正确地将该条件放入ON子句中: http : //sqlfiddle.com/#!2/8936b5/3/0

(notice the FUNCTIONAL difference, the result is not the same, because the queries are not functionally equivalent) (请注意,FUNCTIONAL有所不同,结果不一样,因为查询在功能上不相同)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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