验证表里某不确定的字段的值是否唯一的方法?
如果可以改数据表,你加上一个 唯一约束 unique;如果不能,查询的时候可以用 group by 分组
不可以。。加唯一约束。字段很多。这个是自定义字段的话,不可以加约束
你这个问题是否可以理解为“验证表里的某一不确定的字段的值,没有重复”?
如果是的话,那么你就可以先查出表的总记录数,然后在查出该字段去重之后的总记录数,
对比两次结果,如果数量相同则没有重复;如果数量不相等,则代表有重复的内容。
下面是一个示例:
mysql> select * from user;
+----+------+-----------+
| id | name | address |
+----+------+-----------+
| 1 | aaa | beijing |
| 2 | bbb | shanghai |
| 3 | ccc | hangzhou |
| 5 | aaa | chongqing |
+----+------+-----------+
4 rows in set (0.00 sec)
mysql> select (select count(*) from user) = (select count(*) from (select distinct name from user) t);
+-----------------------------------------------------------------------------------------+
| (select count(*) from user) = (select count(*) from (select distinct name from user) t) |
+-----------------------------------------------------------------------------------------+
| 0 |
+-----------------------------------------------------------------------------------------+
1 row in set (0.01 sec)
mysql> delete from user where id=5;
Query OK, 1 row affected (0.05 sec)
mysql> select * from user;
+----+------+----------+
| id | name | address |
+----+------+----------+
| 1 | aaa | beijing |
| 2 | bbb | shanghai |
| 3 | ccc | hangzhou |
+----+------+----------+
3 rows in set (0.00 sec)
mysql> select (select count(*) from user) = (select count(*) from (select distinct name from user) t);
+-----------------------------------------------------------------------------------------+
| (select count(*) from user) = (select count(*) from (select distinct name from user) t) |
+-----------------------------------------------------------------------------------------+
| 1 |
+-----------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
要考虑数据很多的情况,这个直接查表不可以。。
执行以下sql查出来的字段的值都是唯一的
select t.YOUR_COLUMN
from YOUR_TABLE t
group by t.YOUR_COLUMN
having count(t.YOUR_COLUMN) = 1