[英]MySQL select all rows with the same group of id
I'm using using MySql 5.7.18 and PHP 7.我正在使用 MySql 5.7.18 和 PHP 7。
I have this table:我有这张桌子:
id | object_id | item_id
-------------------------
1 1 2
2 1 3
3 1 4
4 2 5
5 2 3
6 3 2
7 3 3
8 3 4
9 4 2
10 5 1
11 5 3
12 5 5
13 6 2
14 6 3
15 6 4
So I need to select the reference object by id, for example I'll take the object_id 1
and take his items, so in my code I'll get:所以我需要 select 通过 id 引用 object ,例如我将取 object_id
1
并取他的物品,所以在我的代码中我会得到:
$object_id = 1;
$item_ids = [2, 3, 4];
Now I want to get all object_id
who have the same group of item_id
.现在我想获取所有具有同一组
item_id
的object_id
。 So here I need to get the object_id 3 and 6
because all of them have the same item_id
than the object 1.所以在这里我需要获取
object_id 3 and 6
,因为它们都具有与object 1相同的item_id
。
Another example if I have the object_id
2 in reference I'll get no result because there are no row with the same group ids.另一个示例,如果我有
object_id
2 引用,我将不会得到任何结果,因为没有具有相同组 id 的行。
It is possible to do that with SQL query or I have to do it in my code?可以使用 SQL 查询来做到这一点,还是我必须在我的代码中做到这一点?
Yes it seems possible by concatenation, here it is:是的,它似乎可以通过连接来实现,这里是:
select a.* from (
select object_id, group_concat(item_id order by id separator '-') as item_list
from test group by object_id
) a where a.item_list = '2-3-4'
Here's the fiddle:这是小提琴:
http://sqlfiddle.com/#!9/6360bc/6 http://sqlfiddle.com/#!9/6360bc/6
If you want to query by object ID:如果要通过object ID查询:
select a.* from (
select object_id, group_concat(item_id order by id separator '-') as item_list
from test group by object_id
) a where a.item_list = (
select group_concat(item_id order by id separator '-')
from test where object_id = 1
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.