0

我在 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关键字。?

4

4 回答 4

1

您可以使用EXISTS

WHERE EXISTS
       ( SELECT 1
           FROM shares
          WHERE share_id = 7
            AND stores_id = stores.id
       )

JOIN

JOIN shares
  ON shares.stores_id = stores.id
 AND shares.share_id = 7

(请注意,JOIN可能会返回某些商店的多个副本,但因为UNIONSELECT DISTINCT实际上不会影响您的最终结果集。)

于 2012-07-13T21:03:32.060 回答
0

这可以帮助您:

select stores.id from stores where user_id = 7  
UNION  
select s1.id from stores s1 
       inner join shares s2 
       on s2.share_id = 7 
       and s1.id = s2.stores_id;
于 2012-07-13T21:01:57.947 回答
0

如果你只需要身份证,这会很好......

SELECT stores.id
FROM   stores
WHERE  user_id = 7

UNION

SELECT stores_id as id
FROM   shares
WHERE  share_id = 7

但是,如果您需要来自 stores 表中其他列的一些数据,则 INNER JOIN 或 EXISTS 将是您最好的选择。

于 2012-07-13T21:06:50.503 回答
0

左连接应该完成您正在寻找的内容:

select distinct stores.id 
from stores 
left join shares on stores.id = shares.stores_id
where stores.user_id = 7 
or shares.share_id = 7
于 2012-07-13T21:07:12.037 回答