MySQL两个表的交集

时间:2015-11-30 03:18:56

标签: mysql join

我需要实现一个函数,它返回安装不属于的所有网络。 以下是我的表格,例如,如果我的安装ID为1,并且我需要安装不属于的所有网络ID,那么结果将仅为[9]

network_id  |   installation_id
-------------------------------
    1       |       1
    3       |       1
    2       |       1    
    2       |       2
    9       |       2
    2       |       3    

我知道这可以通过连接查询来解决,但我不确定如何为同一个表实现它。这是我迄今为止所尝试过的。

select * from network_installations where installation_id = 1;

network_id  |   installation_id
-------------------------------
    1       |       1
    2       |       1
    3       |       1

select * from network_installations where installation_id != 1;

network_id  |   installation_id
-------------------------------
    9       |       2
    2       |       2
    2       |       3

两个表的交集将产生预期的答案,即[9]。但是虽然我们有union,但{mys}中没有intersect。找到上述两个查询的intersection的解决方案或使用single query using join实现它的提示将非常感激。

3 个答案:

答案 0 :(得分:1)

执行此操作的最佳方法是使用network表(我认为存在):

select n.*
from network n
where not exists (select 1
                  from network_installation ni
                  where ni.network_id = n.network_id and
                        ni.installation_id = 1
                 );

如果您以某种方式没有网络表,则可以将from子句替换为:

from (select distinct network_id from network_installation) n

编辑:

您可以在没有子查询的单个查询中执行此操作,但join是多余的。只需使用group by

select ni.network_id
from network_installation ni
group by ni.network_id
having sum(ni.installation_id = 1) = 0;

having子句计算每个网络ID的给定安装的匹配数。 = 0表示没有。

答案 1 :(得分:1)

使用OUTER JOIN的另一种解决方案:

SELECT t1.network_id, t1.installation_id, t2.network_id, t2.installation_id
FROM tab t1 LEFT JOIN tab t2
    ON t1.network_id = t2.network_id AND t2.installation_id = 1
WHERE t2.network_id IS NULL

您可以在http://www.sqlfiddle.com/#!9/4798d/2

查看

答案 2 :(得分:0)

select * 
from network_installations 
where network_id in
    (select network_id 
     from network_installations 
     where installation_id = 1
     group by network_id )
相关问题