1. 程式人生 > >資料庫學習系列之查重複值

資料庫學習系列之查重複值

CREATE TABLE contacts (
id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(255) NOT NULL
);
INSERT INTO contacts (first_name,last_name,email) ;
VALUES ('Carine ',‘Schmitt’,‘[email protected]’),
(‘Jean’,‘King’,‘[email protected]

’),
(‘Peter’,‘Ferguson’,‘[email protected]’),
('Janine ',‘Labrune’,‘[email protected]’),
('Jonas ',‘Bergulfsen’,‘[email protected]’),
('Janine ',‘Labrune’,‘[email protected]’),
(‘Susan’,‘Nelson’,‘[email protected]’),
('Zbyszek ',‘Piestrzeniewicz’,‘[email protected]’),
(‘Roland’,‘Keitel’,‘
[email protected]
’),
(‘Julie’,‘Murphy’,‘[email protected]’),
(‘Kwai’,‘Lee’,‘[email protected]’),
(‘Jean’,‘King’,‘[email protected]’),
(‘Susan’,‘Nelson’,‘[email protected]’),
(‘Roland’,‘Keitel’,‘[email protected]’);
SELECT * FROM contacts;
#根據一個列找到重複的行的個數
SELECT c.first_name , COUNT(c.first_name)
FROM
contacts c GROUP BY c.first_name
HAVING COUNT(c.first_name)>1;
#根據多個列找到重複的值,原理一樣
SELECT
c.first_name,COUNT(c.first_name),
c.last_name,COUNT(c.last_name),
c.email,COUNT(c.email)
FROM contacts c
GROUP BY
c.first_name,
c.last_name,
c.email
HAVING COUNT(c.first_name)>1
AND COUNT(c.last_name)>1
AND COUNT(c.email)>1;