php - MySQL 选择具有同一组 id 的所有行

标签 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];

现在我想获取所有具有相同 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/

相关文章:

php - Windows 上 PHP 的常见安装路径

PHP 添加单引号到逗号分隔列表

php - 创建指向 google play 应用程序下载的直接链接

mysql - MySQL 中不可打印的字符

MYSQL 选择最大购买金额

php - 如何在 Zend\Db (Zend Framework 2) 中处理多对多关系

php - 从postgresql中的序列化php数组中提取值

php - 更改 PHP 代码以允许传递唯一 ID

javascript - NodeJS SQL 在 for 循环中返回 'Cannot read property ' x' of undefined'

mysql - SQL连接不完整的表