如何在 MySQL 中選擇滿足不同行不同條件的值?
您可以使用 IN() 和 GROUP BY 來選擇滿足不同行不同條件的值。語法如下:
SELECT yourColumnName1 from yourTableName WHERE yourColumnName2 IN(value1,value2,.....N) GROUP BY yourColumnName1 HAVING COUNT(DISTINCT yourColumnName2)=conditionValue;
為了理解上述語法,讓我們首先建立一個表。建立表的查詢如下:
mysql> create table DifferentRows -> ( -> FirstRow int, -> SecondRow int -> ); Query OK, 0 rows affected (0.72 sec)
使用 insert 命令在表中插入一些記錄。查詢如下:
mysql> insert into DifferentRows values(10,10); Query OK, 1 row affected (0.15 sec) mysql> insert into DifferentRows values(10,100); Query OK, 1 row affected (0.17 sec) mysql> insert into DifferentRows values(10,300); Query OK, 1 row affected (0.16 sec) mysql> insert into DifferentRows values(20,100); Query OK, 1 row affected (0.18 sec)
使用 select 語句顯示錶中的所有記錄。查詢如下:
mysql> select *from DifferentRows;
以下是輸出。
+----------+-----------+ | FirstRow | SecondRow | +----------+-----------+ | 10 | 10 | | 10 | 100 | | 10 | 300 | | 20 | 100 | +----------+-----------+ 4 rows in set (0.00 sec)
以下是如何選擇滿足不同行不同條件的值的查詢。這將給出所有具有 SecondRow 為 10、100、300 的不同的 FirstRow 記錄。
mysql> select FirstRow from DifferentRows -> where SecondRow IN(10,100,300) -> group by FirstRow -> having count(distinct SecondRow)=3;
以下是輸出。
+----------+ | FirstRow | +----------+ | 10 | +----------+ 1 row in set (0.00 sec)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP