【问题标题】:SQL select distinct where exist row for each id in other tableSQL为其他表中的每个ID选择不同的存在行
【发布时间】:2014-09-25 11:59:57
【问题描述】:

我的表 A 和 B 有一个关系:A n1 B 关系。

它们通过字段 A.b = B.id 连接,其中 B.id 是唯一的

我有一个参数是 B 的一堆 id。

我想获得具有 all 给定 B.id 分配的不同 A.id。

示例:

表 B

| id | ...
| 1  |
| 2  |
| 3  |

表 A

| id |  b  | ...
| 1  |  1  |
| 1  |  2  |
| 1  |  3  |
| 2  |  1  |
| 2  |  2  |
               <-- id=2 is not assigned to b=3 !
| 3  |  1  |
| 3  |  2  |
| 3  |  3  |

参数 B.ids="1,2,3" 的预期结果:1、3(2 未达到所需的 B.id=3)

我该怎么做?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您可以使用聚合和having 子句来做到这一点:

    select id
    from tableA a join
         tableB b
         on a.b = b.id
    group by id
    having count(distinct b) = (select count(distinct b) from tableB);
    

    请注意,这可以通过一些假设来简化。例如,如果您知道 b id 是唯一的,那么您不需要 count(distinct)count() 就足够了。)

    编辑:

    如果你想要一个你想要检查的 id 列表,你可以使用:

    select id
    from tableA a
    where find_in_set(a.b, IDLISTHERE) > 0
    group by id
    having count(distinct b) = (select count(distinct b) from tableB where find_in_set(a.b, IDLISTHERE) > 0);
    

    【讨论】:

    • for param="1,2,3": 可能添加:"having count(b) = :param_size where b.id IN (:param)"
    【解决方案2】:
    select id  from tableA a join tableB b  on a.b = b.id
    group by id
    having count(distinct b) = (select count(distinct b) from tableB);
    

    【讨论】:

    • 那是 Gordon Linoff 已经发布的内容,但是参数在哪里?我只想要表 A 中那些分配给由参数定义的 B 选择的那些。
    猜你喜欢
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多