MySQL 选择两列值不同的行?
你可以使用 MySQL 的 != 运算符。语法如下
SELECT *FROM yourTableName WHERE yourColumnName1 !=yourColumnName2 OR (yourColumnName1 IS NULL AND yourColumnName2IS NOT NULL) OR (yourColumnName2 IS NULL AND yourColumnName1 IS NOT NULL);
为了理解上述语法,我们创建一个表。创建表的查询如下
mysql> create table selectTwoColumns -> ( -> Id int NOT NULL AUTO_INCREMENT, -> FirstNumber int, -> SecondNumber int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.87 sec)
使用插入命令向表中插入一些记录。查询如下
mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(10,20); Query OK, 1 row affected (0.29 sec) mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(30,40); Query OK, 1 row affected (0.16 sec) mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(20,20); Query OK, 1 row affected (0.15 sec) mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(50,60); Query OK, 1 row affected (0.18 sec) mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(50,50); Query OK, 1 row affected (0.17 sec) mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(70,NULL); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录。查询如下
mysql> select *from selectTwoColumns;
以下是输出
+----+-------------+--------------+ | Id | FirstNumber | SecondNumber | +----+-------------+--------------+ | 1 | 10 | 20 | | 2 | 30 | 40 | | 3 | 20 | 20 | | 4 | 50 | 60 | | 5 | 50 | 50 | | 6 | 70 | NULL | +----+-------------+--------------+ 6 rows in set (0.00 sec)
以下是选择两列不具有相同值的行的查询
mysql> select *from selectTwoColumns -> where FirstNumber!=SecondNumber -> OR (FirstNumber IS NULL AND SecondNumber IS NOT NULL) -> OR (SecondNumber IS NULL AND FirstNumber IS NOT NULL);
以下是输出
+----+-------------+--------------+ | Id | FirstNumber | SecondNumber | +----+-------------+--------------+ | 1 | 10 | 20 | | 2 | 30 | 40 | | 4 | 50 | 60 | | 6 | 70 | NULL | +----+-------------+--------------+ 4 rows in set (0.00 sec)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP