Mysql SQL为其他表中的每个id选择不同的where exist行
表A和表B有一个关系:A和B的关系 它们通过字段A.b=b.id连接,其中b.id是唯一的 我有一个参数,它是一组B的id 我想得到分配了所有给定B.id的不同A.id 示例: 表BMysql SQL为其他表中的每个id选择不同的where exist行,mysql,sql,Mysql,Sql,表A和表B有一个关系:A和B的关系 它们通过字段A.b=b.id连接,其中b.id是唯一的 我有一个参数,它是一组B的id 我想得到分配了所有给定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 assign
| 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 |
| id | b |。。。
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 2 |
您可以通过聚合和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);
这是Gordon Linoff已经发布的,但参数在哪里?我只想要表A中指定给参数定义的b选择的那些。for param=“1,2,3”:可以添加:“having count(b)=:param_size,其中b.id IN(:param)”
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);