我有一对多关系表。
我希望得到多个id之间共享的最低的other_id。
id other_id
5 5
5 6
5 7
6 6
6 7
7 7
我可以通过动态构建一个SQL语句来实现这一点,并为我想要查询的每个附加id添加一些部分。例如:
select * from (
select other_id from SomeTable where id = 5
) as a
inner join (
select other_id from SomeTable where id = 6
) as b
inner join (
select other_id from SomeTable where id = 7
) as c
on a.other_id = b.other_id
and a.other_id = c.other_id
有更好的方法吗?更具体地说,有没有办法做到这一点,不需要可变数量的连接?我觉得这个问题可能已经有了一个名字和更好的解决方案。
我的查询给了我7号,这就是我想要的。
答案 0 :(得分:1)
我目前没有测试它的mysql服务器,但尝试“分组依据”声明:
select
other_id
from
SomeTable
group by
other_id having count(*) > 1
order by
other_id asc
limit 1
答案 1 :(得分:0)
使用MIN进行简单查询
SELECT MIN(other_id) FROM table
答案 2 :(得分:0)
所有ID之间共享的最低other_id
select other_id
from SomeTable
group by other_id
having count(distinct id) = 3
order by other_id limit 1
或动态
select other_id
from SomeTable
group by other_id
having count(distinct id) = (select count(distinct id) from SomeTable)
order by other_id limit 1
或者如果您想查找特定ID之间共享的最低other_id
select other_id
from SomeTable
where id in (5,6,7)
group by other_id
having count(distinct id) = 3
order by other_id limit 1
答案 3 :(得分:0)
虽然,似乎有工作解决方案我想添加我的版本,只是为了展示,我有多聪明; - )
SELECT other_id FROM SomeTable a INNER JOIN SomeTable b on a.other_id=b.other_id ORDER by other_id ASC LIMIT 1