0

I am using mysql db.

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

I want to write such a query so that o/p will be like this-:

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

So I want Accounting, Shiping, Receiving and testing comments.

Can anybody plz guide me??

4

2 回答 2

1
  • 如果您只想要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)

于 2012-10-02T10:48:34.920 回答
0

是否要选择所有包含 4 条评论的 ID?在您的示例中,1121 有 4 个不同的评论(就像“状态”,对吗?),而 1122 只有 2 个状态(评论)。

select T1.id from mytable T1, mytable T2, mytable T3, mytable T3 where T2.id=T1.id and T3.id=T1.id and T4.id=T1.id and T1.comment='Accounting' and T2.comment='Shipping' and T3.comment='Receiving' and T4.id='Shipping'
于 2012-09-30T16:22:38.407 回答