使用 MySQL 获取另一列中具有两个不同值的记录
为此,你可以使用 GROUP BY HAVING 子句。
我们先创建一个表 -
mysql> create table DemoTable751 ( StudentName varchar(100), SubjectName varchar(100) ); Query OK, 0 rows affected (0.66 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable751 values('John','MySQL'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable751 values('John','MongoDB'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable751 values('Sam','MySQL'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable751 values('Carol','Java'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable751 values('David','MySQL'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable751 values('Carol','MongoDB'); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable751;
这将产生以下输出 -
+-------------+-------------+ | StudentName | SubjectName | +-------------+-------------+ | John | MySQL | | John | MongoDB | | Sam | MySQL | | Carol | Java | | David | MySQL | | Carol | MongoDB | +-------------+-------------+ 6 rows in set (0.00 sec)
以下是使用 MySQL 获取另一列中具有两个不同值的记录的查询 -
mysql> select StudentName from DemoTable751 group by StudentName having count(SubjectName) > 1;
这将产生以下输出 -
+-------------+ | StudentName | +-------------+ | John | | Carol | +-------------+ 2 rows in set (0.00 sec)
广告