MySQL 查询如何按另一列分组来选择列值仅为 0 的行?
为此,请使用 group by。让我们首先创建一个表 -
mysql> create table DemoTable1344 -> ( -> `SequenceId` int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientId int, -> isMarried tinyint(1) -> ); Query OK, 0 rows affected (0.49 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1344(ClientId,isMarried) values(4567,0); Query OK, 1 row affected (0.45 sec) mysql> insert into DemoTable1344(ClientId,isMarried) values(9876,0); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1344(ClientId,isMarried) values(5432,1); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1344(ClientId,isMarried) values(4567,1); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1344(ClientId,isMarried) values(9873,0); Query OK, 1 row affected (0.15 sec)
使用 select 语句从表中显示所有记录 -
mysql> select * from DemoTable1344;
这将产生以下输出 -
+------------+----------+-----------+ | SequenceId | ClientId | isMarried | +------------+----------+-----------+ | 1 | 4567 | 0 | | 2 | 9876 | 0 | | 3 | 5432 | 1 | | 4 | 4567 | 1 | | 5 | 9873 | 0 | +------------+----------+-----------+ 5 rows in set (0.00 sec)
以下是按另一列分组来选择列值仅为 0 的行的查询 -
mysql> select SequenceId,ClientId,isMarried -> from DemoTable1344 -> group by ClientId -> having isMarried=0;
这将产生以下输出 -
+------------+----------+-----------+ | SequenceId | ClientId | isMarried | +------------+----------+-----------+ | 1 | 4567 | 0 | | 2 | 9876 | 0 | | 5 | 9873 | 0 | +------------+----------+-----------+ 3 rows in set (0.00 sec)
广告