我在 mysql 数据库中有 2 个表存储和共享。我试图避免 IN 子句。请参阅下文了解更多详情
select id, user_id from stores where user_id =7;
+----+---------+
| id | user_id |
+----+---------+
| 36 | 7 |
| 37 | 7 |
select stores_id,share_id from shares where share_id=7;
+-----------+----------+
| stores_id | share_id |
+-----------+----------+
| 15 | 7 |
| 38 | 7 |
现在我运行这个
SELECT stores.id
FROM stores
WHERE user_id = 7
UNION
(SELECT stores.id
FROM stores
WHERE id IN (SELECT stores_id
FROM shares
WHERE share_id = 7));
要得到以下结果:
+----+
| id |
+----+
| 36 |
| 37 |
| 15 |
| 38 |
+----+
问题 如何重写查询以便不使用 IN 关键字。?
最佳答案
您可以使用EXISTS
:
WHERE EXISTS
( SELECT 1
FROM shares
WHERE share_id = 7
AND stores_id = stores.id
)
或加入
:
JOIN shares
ON shares.stores_id = stores.id
AND shares.share_id = 7
(请注意,JOIN
可能会返回某些存储的多个副本,但由于 UNION
暗示 SELECT DISTINCT
,因此实际上不会影响您的最终结果集。)
关于mysql - SQL 条件连接挑战,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11478287/