gpt4 book ai didi

mysql - 查询获取mysql中同一列中的多个字段

转载 作者:行者123 更新时间:2023-11-29 14:15:58 25 4
gpt4 key购买 nike

我正在使用 mysql 数据库。

     id | comment       
--------+---------------
1121 | Accounting
1121 | Shipping
1121 | Receiving
1121 | Testing
1122 | Accounting
1122 | Receiving

我想写这样一个查询,这样o/p就会像这样-:

     id | comment       
--------+---------------
1121 | Accounting
1121 | Shipping
1121 | Receiving
1121 | Testing

所以我想要会计、运输、接收和测试评论。

有人可以指导我吗?

最佳答案

  • 如果您只需要包含所有四个评论的记录的 id,您可以按 id 进行分组,并过滤​​此类组以查找包含所需数量的记录记录数:

    SELECT   id
    FROM my_table
    WHERE comment IN ('Accounting', 'Shipping', 'Receiving', 'Testing')
    GROUP BY id
    HAVING COUNT(*) = 4

    查看 sqlfiddle .

  • 如果您想要此类(id, comment)对的完整记录,您可以将结果与原始表连接起来:

    SELECT * FROM my_table NATURAL JOIN (
    SELECT id
    FROM my_table
    WHERE comment IN ('Accounting', 'Shipping', 'Receiving', 'Testing')
    GROUP BY id
    HAVING COUNT(*) = 4
    ) t
    WHERE comment IN ('Accounting', 'Shipping', 'Receiving', 'Testing')

    查看 sqlfiddle .

请注意,如果您的数据模型不能保证 (id, comment) 对的唯一性,则需要将 COUNT(*) 替换为(性能较差的)上述查询中的 COUNT(DISTINCT comment)

关于mysql - 查询获取mysql中同一列中的多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12662553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com