MySQL选择具有相同ID组的所有行

时间:2019-10-23 13:28:43

标签: php mysql

我正在使用MySql 5.7.18和PHP 7。

我有这张桌子:

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

因此,我需要通过id选择参考对象,例如,我将使用object_id 1并获取他的项目,因此在我的代码中,我将得到:

$object_id = 1;
$item_ids = [2, 3, 4];

现在,我想让所有object_id拥有同一组item_id。因此,在这里我需要获取object_id 3 and 6,因为它们都与对象1具有相同的item_id

另一个示例,如果引用中有object_id 2,将不会有任何结果,因为没有行具有相同的组ID。

使用SQL查询可以做到这一点,还是必须在我的代码中完成?

1 个答案:

答案 0 :(得分:3)

是的,似乎可以通过串联来实现,这里是:

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'

这是小提琴:

http://sqlfiddle.com/#!9/6360bc/6


如果要按对象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
)