您可以使用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) -> );
使用insert命令在表中插入一些记录。查询如下:
mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(10,20); mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(30,40); mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(20,20); mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(50,60); mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(50,50); mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(70,NULL);
使用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)