检查 MySQL 中某一列是否具有唯一值
您可为此使用子查询。让我们首先创建一个演示表
mysql> create table uniqueBothColumnValueSameDemo -> ( -> UserId int, -> UserValue int -> ); Query OK, 0 rows affected (0.64 sec)
使用插入命令在表中插入一些记录。查询如下所示 −
mysql> insert into uniqueBothColumnValueSameDemo values(10,20); Query OK, 1 row affected (0.21 sec) mysql> insert into uniqueBothColumnValueSameDemo values(10,20); Query OK, 1 row affected (0.09 sec) mysql> insert into uniqueBothColumnValueSameDemo values(20,30); Query OK, 1 row affected (0.10 sec) mysql> insert into uniqueBothColumnValueSameDemo values(20,40); Query OK, 1 row affected (0.11 sec) mysql> insert into uniqueBothColumnValueSameDemo values(50,10); Query OK, 1 row affected (0.10 sec) mysql> insert into uniqueBothColumnValueSameDemo values(50,10); Query OK, 1 row affected (0.07 sec) mysql> insert into uniqueBothColumnValueSameDemo values(60,30); Query OK, 1 row affected (0.07 sec) mysql> insert into uniqueBothColumnValueSameDemo values(60,30); Query OK, 1 row affected (0.08 sec) mysql> insert into uniqueBothColumnValueSameDemo values(60,50); Query OK, 1 row affected (0.12 sec)
使用 select 语句显示表中的所有记录。查询如下所示 −
mysql> select *from uniqueBothColumnValueSameDemo;
输出如下所示
+--------+-----------+ | UserId | UserValue | +--------+-----------+ | 10 | 20 | | 10 | 20 | | 20 | 30 | | 20 | 40 | | 50 | 10 | | 50 | 10 | | 60 | 30 | | 60 | 30 | | 60 | 50 | +--------+-----------+ 9 rows in set (0.00 sec)
这是检查列中是否存在唯一值所需的查询
mysql> SELECT DISTINCT UserId, UserValue -> FROM uniqueBothColumnValueSameDemo tbl1 -> WHERE (SELECT count(DISTINCT UserValue) -> FROM uniqueBothColumnValueSameDemo tbl2 -> WHERE tbl2.UserId = tbl1.UserId) = 1;
输出如下所示
+--------+-----------+ | UserId | UserValue | +--------+-----------+ | 10 | 20 | | 50 | 10 | +--------+-----------+ 2 rows in set (0.00 sec)
广告