标签:int may tab 统计 ima uniq san and 重复记录
你可以在 MySQL 数据表中设置指定的字段为 PRIMARY KEY(主键) 或者 UNIQUE(唯一) 索引来保证数据的唯一性。
CREATE TABLE person_tbl
(
first_name CHAR(20) NOT NULL,
last_name CHAR(20) NOT NULL,
sex CHAR(10),
PRIMARY KEY (last_name, first_name)
);
insert into person_tbl values (‘zhang‘,‘san‘,‘男‘);
insert into person_tbl values (‘zhang‘,‘san‘,‘男‘);
1062 - Duplicate entry ‘san-zhang‘ for key ‘PRIMARY‘
CREATE TABLE person_tbl
(
first_name CHAR(20),
last_name CHAR(20),
sex CHAR(10),
UNIQUE (last_name, first_name)
);
insert into person_tbl values (‘zhang‘,‘san‘,‘男‘);
insert into person_tbl values (‘zhang‘,null,‘男‘);
insert ignore into person_tbl (last_name, first_name) values (‘Jay‘, ‘Thomas‘);
insert ignore into person_tbl (last_name, first_name) values (‘Jay‘, ‘Thomas‘);
mysql> select * from person_tbl;
+------------+-----------+------+
| first_name | last_name | sex |
+------------+-----------+------+
| zhang | san | 男 |
| zhang | NULL | 男 |
| Thomas | Jay | NULL |
+------------+-----------+------+
3 rows in set
replace into person_tbl (last_name, first_name) values (‘Jay‘, ‘Thomas‘);
mysql> select * from person_tbl;
+------------+-----------+------+
| first_name | last_name | sex |
+------------+-----------+------+
| zhang | san | 男 |
| zhang | NULL | 男 |
| Thomas | Jay | NULL |
+------------+-----------+------+
3 rows in set
mysql> select * from person_tbl;
+------------+-----------+------+
| first_name | last_name | sex |
+------------+-----------+------+
| zhang | san | 男 |
| zhang | san | 男 |
| zhang | san | 男 |
| Thomas | Jay | NULL |
| Thomas | Jay | NULL |
| li | san | 男 |
| zhang | si | 男 |
+------------+-----------+------+
7 rows in set
select count(*) repetitions, last_name, first_name
from person_tbl
GROUP BY last_name, first_name
having repetitions > 1;
+-------------+-----------+------------+
| repetitions | last_name | first_name |
+-------------+-----------+------------+
| 3 | san | zhang |
| 2 | Jay | Thomas |
+-------------+-----------+------------+
2 rows in set
以上查询语句将返回 person_tbl 表中重复的记录数。 一般情况下,查询重复的值,请执行以下操作:
如果你需要读取不重复的数据可以在 SELECT 语句中使用 DISTINCT 关键字来过滤重复数据。
select distinct last_name, first_name from person_tbl;
+-----------+------------+
| last_name | first_name |
+-----------+------------+
| san | zhang |
| Jay | Thomas |
| san | li |
| si | zhang |
+-----------+------------+
4 rows in set
你也可以使用 GROUP BY 来读取数据表中不重复的数据:
select last_name, first_name from person_tbl
group by last_name, first_name;
CREATE TABLE tmp
SELECT last_name, first_name, sex
FROM person_tbl
GROUP BY (last_name, first_name, sex);
DROP TABLE person_tbl;
ALTER TABLE tmp RENAME TO person_tbl;
或者在数据表中添加 INDEX(索引) 和 PRIMAY KEY(主键)这种简单的方法来删除表中的重复记录。方法如下:
ALTER IGNORE TABLE person_tbl ADD PRIMARY KEY (last_name, first_name);
删除重复数据代码实现不了Operand should contain 1 column(s)
标签:int may tab 统计 ima uniq san and 重复记录
原文地址:https://www.cnblogs.com/Stephanie-boke/p/11675203.html