我想只显示一个项目,如果它存在于产品和出价中,但如果id与orders表中的一行匹配,请不要选择它,这是我到目前为止的sql:
SELECT *
FROM products
RIGHT JOIN bids
ON bids.bids_item = id
WHERE username = ?
AND Now() > enddate
AND enabled = 1
GROUP BY bids.bids_item
ORDER BY enddate
如果bid.bids_item作为orders.orders_product存在然后不选择,我试图这样做,但如果没有,则选择该行。我该怎么做呢?
表:
products
id
orders
orders.order_product
答案 0 :(得分:0)
当你说products
和bids
都需要包含在[alias].[column]
和SELECT *
FROM products p
INNER JOIN bids b ON b.bids_item = p.id -- inner join on bids as we only want to include when exists in both p and b
LEFT JOIN orders o ON p.id = o.orders_product
WHERE o.orders_product IS NULL -- left join and filter where p.id does not exist in o
and username = ?
AND Now() > enddate
AND enabled = 1
中时,我对你为什么要使用正确的加入出价感到有点困惑。此外,{{1}}的一致使用将使我更容易理解作为回答者以及将来查看代码的任何人。也就是说,你可以这样做:
{{1}}
答案 1 :(得分:0)
尝试使用NOT IN
的子查询。我不是在为你扭动整个查询,但这个想法是这样的
SELECT * FROM products WHERE bids.bids_item NOT IN ( SELECT orders_product FROM orders);