首页 > 解决方案 > mysql检查产品ID是否也存在于其他表中

问题描述

我对 JOINS 没有太多经验,并且通过下面的查询得到的结果不正确。我有一个名为products的表,想检查表product_links中是否有记录。我只想获取product_links中没有行的项目列表。

当我运行以下查询时,我只得到一行。有人建议吗?谷歌无法帮助我,或者我使用错误的关键字进行搜索。

SELECT a.id, a.SKU, a.title, 
(SELECT COUNT(b.id) AS amount FROM product_links WHERE b.product=a.id) AS amount
FROM products AS a
LEFT JOIN product_links AS b ON b.product=a.id

标签: mysqljoincount

解决方案


我会推荐not exists

select p.*
from products p
where not exists (select 1 from product_links pl where pl.product_id = p.id)

推荐阅读