我对我的 SQL 有点生疏,希望对这些查询有所帮助,我正在努力解决这些问题,甚至想知道是否有可能。
嗨,我有一些桌子;
客户、产品、客户产品
当客户选择使用添加到 clientproducts 的产品时,使用 clientid 和 productid。
简单的查询 我想运行一个查询,它只会向我显示客户选择的产品。
我还想运行一个查询,该查询将只显示尚未选择产品的客户。
提前谢谢你的帮助。
查询一:
SELECT table1.id1 FROM table1
WHERE table1.id1 IN (SELECT table2.foreign_id FROM table2);
查询 2:
SELECT table1.id1 FROM table1
WHERE table1.id1 NOT IN (SELECT table2.foreign_id FROM table2);
在这里,使用LEFT JOIN
SELECT a.*
FROM products a
LEFT JOIN clientproducts b
ON a.productID = b.productID
LEFT JOIN clients c
ON b.clientID = c.clientID AND
c.ClientID = 'clientID HERE'
WHERE c.client IS NULL
或者
SELECT a.*
FROM products a
LEFT JOIN clientproducts b
ON a.productID = b.productID AND
b.ClientID = 'clientID HERE'
WHERE b.productID IS NULL
简单的查询
SELECT * FROM clients LEFT JOIN products ON clients.id = products.client_id
硬查询
SELECT * FROM clients WHERE clients.id NOT IN (SELECT clients.id FROM clients LEFT JOIN products ON clients.id = products.client_id)
获取client_id = 1的所有产品信息
select products.*
from products, clientproducts
where products.id = clientproducts.product_id
and clientproducts.client_id = 1
获取所有未选择任何产品的客户详细信息
select *
from clients
where id not in (select client_id
from clientproducts)