我有这三个表:
产品:
+----+--------------+
| id | product_name |
+----+--------------+
| 12 | a |
| 13 | b |
| 14 | c |
| 15 | d |
| 16 | e |
| 17 | f |
| 18 | g |
| 19 | h |
| 20 | i |
| 21 | j |
+----+--------------+
连接:
+----+------------+----------------------+
| id | product_id | connected_product_id |
+----+------------+----------------------+
| 1 | 21 | 18 |
| 2 | 21 | 19 |
| 3 | 21 | 20 |
+----+------------+----------------------+
提案:
+----+-------------+-------------+
| id | proposer_id | receiver_id |
+----+-------------+-------------+
| 2 | 21 | 16 |
| 3 | 21 | 17 |
| 4 | 21 | 18 |
+----+-------------+-------------+
对于某些产品X,我希望获得所有与X无关的产品,并且它们之间没有任何建议(X和那些产品,不是提议者,也不是彼此的接收者)。
我正在尝试这个简陋的陈述:
SELECT *
FROM products
WHERE id != X_id
AND id NOT IN (
SELECT connected_product_id
FROM connections
WHERE product_id = X_id
)
但是这让我得到了所有未连接到X的产品。
我需要最后一步,我想做这样的事情:
SELECT *
FROM products
WHERE id != X_id
AND id NOT IN (
SELECT product_id
FROM proposals
WHERE product_id != X_id
AND receiver_id NOT IN (
SELECT connected_product_id
FROM connections
WHERE product_id = X_id
)
)
但对于上述情况,假设产品X为id = 21,则当前输出为:
21以外的所有产品
我希望输出为:
来自12, 13, 14, 15
中ID的产品中的明星(未连接到X = 21,并且它们之间没有提案,X = 21)
+----+--------------+
| id | product_name |
+----+--------------+
| 12 | a |
| 13 | b |
| 14 | c |
| 15 | d |
+----+--------------+
我使用javascript,因此结果将是一个对象数组{id,product_name}
任何帮助?
答案 0 :(得分:2)
试试这个:
SELECT *
FROM products
WHERE id != 21
AND id NOT IN (
SELECT connected_product_id
FROM connections
WHERE product_id = 21
UNION ALL
SELECT receiver_id
FROM proposals
WHERE proposer_id =21
)
| id | product_name |
|----|--------------|
| 12 | a |
| 13 | b |
| 14 | c |
| 15 | d |
答案 1 :(得分:1)
你有大概是正确的,但有以下两个错误:
product_id
proposer_id
!=
内部not in
创建了一个双倍
负。正确的陈述应该是这样的:
select * from products where
id not in (select connected_product_id from connections where product_id = 21)
and id not in (select receiver_id from proposals where proposer_id = 21)
and id != 21;