SQL条件连接挑战

时间:2012-07-13 20:59:27

标签: mysql sql join conditional

我在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 个答案:

答案 0 :(得分: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可能会返回某些商店的多个副本,但由于UNION暗示SELECT DISTINCT,这实际上不会影响您的最终结果集。)

答案 1 :(得分: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;

答案 2 :(得分:0)

如果你需要的只是身份证,那就可以了......

SELECT stores.id
FROM   stores
WHERE  user_id = 7

UNION

SELECT stores_id as id
FROM   shares
WHERE  share_id = 7

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

答案 3 :(得分: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