繁体   English   中英

当不在表b中时从表a中选择

[英]selecting from table a when not in table b

以下命令从“库存”中选择所有出现在“项目”中且具有正确orderRef的项目。

SELECT a.* FROM stock a LEFT JOIN items b ON a.id = b.stockId WHERE b.orderRef='orderRef'

这可行,但我需要使用正确的orderRef在表“项目”中未列出的所有项目。

我以为应该将“ ON”更改为相反的名称,但“ OFF”无效。

进行“不在”查询的最佳方法是使用MySQL:

select s.*
from stock s
where not exists (select 1 from items i where s.id = i.stockID and i.orderref = 'orderref' limit 1)

MySQL优化器的工作方式最好, not exists 可以通过在items.stockID上建立索引来进一步增强此功能。

请注意,使用左外部联接时,如果第二个表中有重复项,则可能会无意中乘以行的数字。

试试这个:

SELECT a.* FROM stock a LEFT JOIN items b ON a.id = b.stockId WHERE 
                b.stockId is null and a.orderRef='orderRef'

暂无
暂无

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

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