MySQL 选择两列不具有相同值的行?

mysqlmysqli database

您可以使用 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)

使用 insert 命令在表中插入一些记录。 查询语句如下:

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)

相关文章