檢查 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)

更新日期:2019 年 7 月 30 日

418 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.