![](/img/trans.png)
[英]MySQL- How to fetch multiple values of same column using a single SQL query?
[英]Query to fetch multiple fields in same column in mysql
我正在使用mysql db。
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)
。
您是否要選擇所有具有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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.