1、題目:
編寫乙個 sql 查詢,來刪除 person 表中所有重複的電子郵箱,重複的郵箱裡只保留 id 最小 的那個。
+----+------------------+
| id | email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
+----+------------------+
id 是這個表的主鍵。
例如,在執行你的查詢語句之後,上面的 person 表應返回以下幾行:
+----+------------------+
| id | email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
+----+------------------+
執行 sql 之後,輸出是整個 person 表。
使用 delete 語句。
2、解題步驟:
(1) 建立表:
create table `person` (
`personid` int(11) not null auto_increment comment 'personid',
`firstname` varchar(50) character set utf8 collate utf8_general_ci not null comment '名',
`lastname` varchar(50) character set utf8 collate utf8_general_ci not null comment '姓',
`email` varchar(50) character set utf8 collate utf8_general_ci default null comment '電子郵箱',
primary key (`personid`) using btree
) engine = innodb auto_increment = 5 character set = utf8 collate = utf8_general_ci row_format = dynamic;
(2) 插入資料:
insert into `person` values (1, 'xuejin', 'cao', '[email protected]');
insert into `person` values (2, '麻花', '重慶', '[email protected]');
insert into `person` values (3, '公尺線', '雲南', '[email protected]');
insert into `person` values (4, '花生', '山西', '[email protected]');
(3) 查詢sql:
a、方案一:
# 查詢需要刪除的資料
select * from person a, person b where a.email = b.email and a.personid > b.personid;
# 刪除資料
delete a from person a, person b where a.email = b.email and a.personid > b.personid;
b、方案二:
# 查詢需要刪除的資料
select * from person a join person b on b.email = a.email where a.personid > b.personid;
# 刪除資料
delete a from person a join person b on b.email = a.email where a.personid > b.personid;
(4) 執行結果:
a、刪除前:
b、刪除後:
LeetCode MySQL日期比較函式
leetcode題目 表 weather column name type id int recorddate date temperature int id 是這個表的主鍵 該錶包含特定日期的溫度資訊 編寫乙個 sql 查詢,來查詢與之前 昨天的 日期相比溫度更高的所有日期的 id 返回結果 不要...
leetcode mysql 從不訂購的客戶
1 題目 某 包含兩個表,customers 表和 orders 表。編寫乙個 sql 查詢,找出所有從不訂購任何東西的客戶。customers 表 id name 1 joe 2 henry 3 sam 4 max orders 表 id customerid 1 3 2 1 例如給定上述 你的查...
627 交換工資 Leetcode Mysql
給定乙個 salary 表,如下所示,有 m 男性 和 f 女性 的值。交換所有的 f 和 m 值 例如,將所有 f 值更改為 m,反之亦然 要求只使用乙個更新 update 語句,並且沒有中間的臨時表。注意,您必只能寫乙個 update 語句,請不要編寫任何 select 語句。例如 id nam...