[英]Query to fetch multiple fields in same column in mysql
I am using mysql db. 我正在使用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-: 我想编写这样的查询,以便o / p像这样:
id | comment
--------+---------------
1121 | Accounting
1121 | Shipping
1121 | Receiving
1121 | Testing
So I want Accounting, Shiping, Receiving and testing comments. 所以我要记帐,发货,接收和测试注释。
Can anybody plz guide me?? 有人可以引导我吗?
If you only want the id
of records that contain all four comments, you can group by id
and filter such groups for those that contain the requisite number of records: 如果只希望包含所有四个注释的记录的
id
,则可以按id
进行分组,并为包含必需数量的记录的组过滤这些组:
SELECT id FROM my_table WHERE comment IN ('Accounting', 'Shipping', 'Receiving', 'Testing') GROUP BY id HAVING COUNT(*) = 4
If you want the complete records for such (id, comment)
pairs, you can join the result with your original table: 如果您想要此类
(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')
Note that if your data model does not guarantee uniqueness of (id, comment)
pairs, you will need to replace COUNT(*)
with (the less performant) COUNT(DISTINCT comment)
in the above queries. 请注意,如果您的数据模型不能保证
(id, comment)
对的唯一性,则在上述查询中,您需要将COUNT(*)
替换为(性能较低的) COUNT(DISTINCT comment)
。
Do you want to select all IDs, that have all 4 comments? 您是否要选择所有具有4条注释的ID? In your example 1121 has 4 different comments (it's like a "state", right?), and 1122 has only 2 states (comments).
在您的示例中,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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.