Php MySQL选择具有相同id组的所有行
我使用的是MySql 5.7.18和PHP7 我有这张桌子:Php MySQL选择具有相同id组的所有行,php,mysql,Php,Mysql,我使用的是MySql 5.7.18和PHP7 我有这张桌子: 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
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选择引用对象,例如,我将获取对象_id 1并获取他的项目,因此在我的代码中,我将获得:
$object_id = 1;
$item_ids = [2, 3, 4];
现在我想得到所有具有相同组item_id的object_id,这里我需要得到object_id 3和6,因为它们都具有与object 1相同的item_id
另一个例子是,如果我在引用中有对象_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'
这是小提琴:
如果要按对象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
)
是的,通过连接似乎是可能的,这里是:
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'
这是小提琴:
如果要按对象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
)
我正在使用MySql 4.7.3和PHP7。MySQL 4和PHP7。。。。这是否有效?非常确定PHP 7 MySQL客户端不再支持旧的MySQL 4连接协议…@RaymondNijland抱歉,错误的复制粘贴xDIt是phpMyAdmin版本x_xmistakes发生的,甚至可能是MySQL 4.7.3不存在的情况,由于MySQL网站上的手册被删除,我或多或少忘记了MySQL 5.5之前的版本。。我正在使用MySql 4.7.3和PHP7。MySQL 4和PHP7。。。。这是否有效?非常确定PHP 7 MySQL客户端不再支持旧的MySQL 4连接协议…@RaymondNijland抱歉,错误的复制粘贴xDIt是phpMyAdmin版本x_xmistakes发生的,甚至可能是MySQL 4.7.3不存在的情况,由于MySQL网站上的手册被删除,我或多或少忘记了MySQL 5.5之前的版本。但我的评论就不用管了。。。topicstarter复制/粘贴错误:-@RaymondNijland是的,我要删除我的答案,因为我没有mySQL 4.7:谢谢你,塔哈,太棒了!因此,在我的代码中,我必须像组_concat一样转换我的数组,但不要介意我的注释。。。topicstarter复制/粘贴错误:-@RaymondNijland是的,我要删除我的答案,因为我没有mySQL 4.7:谢谢你,塔哈,太棒了!因此,在我的代码中,我必须像组_concat那样转换数组?