我正在使用 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];
现在我想获取所有具有相同 item_id
组的 object_id
。所以在这里我需要获取 object_id 3 和 6
,因为它们都具有与对象 1 相同的 item_id
。
另一个例子,如果我在引用中有 object_id
2,我将得不到任何结果,因为没有行具有相同的组 ID。
可以使用 SQL 查询来完成,还是我必须在我的代码中完成?
最佳答案
是的,通过串联似乎是可能的,这里是:
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'
这是 fiddle :
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
)
关于php - MySQL 选择具有同一组 id 的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524000/