MySQL去重不保留重复元组(mysql不保留重复元祖)

MySQL去重不保留重复元组

在实际的MySQL应用开发中,有时候需要去重,但是又不希望保留重复的元组,这种情况下,我们可以使用MySQL的distinct关键字或者group by语句来实现。

distinct关键字

distinct关键字可以用于查询中,用来去重。

语法如下:

SELECT DISTINCT column1,column2,column3,...
FROM table_name
WHERE [condition];

例如,我们有一个名为“customers”的表,表中包含了顾客的姓名,地址和电话:

+----+----------+-------------------------+-----------------+
| id | name | address | phone |
+----+----------+-------------------------+-----------------+
| 1 | John | No. 888, Mn Street, | 555-555-5555 |
| 2 | Mike | No. 123, Second Street, | 555-555-5556 |
| 3 | David | No. 45, Third Street, | 555-555-5557 |
| 4 | John | No. 999, Fourth Street, | 555-555-5555 |
| 5 | Mike | No. 123, Second Street, | 555-555-5556 |
| 6 | Tom | No. 67, Fifth Street, | 555-555-5558 |
+----+----------+-------------------------+-----------------+

如果我们需要查询“customers”表中不重复的顾客姓名,我们可以执行以下SQL语句:

SELECT DISTINCT name
FROM customers;

执行结果:

+------+
| name |
+------+
| John |
| Mike |
| David|
| Tom |
+------+

group by语句

除了distinct关键字外,我们也可以使用group by语句来实现去重。

语法如下:

SELECT column1,column2,...,function(column)
FROM table_name
WHERE [condition]
GROUP BY column1,column2,...;

例如,我们有一个名为“orders”的表,表中包含了顾客下订单的时间、数量和金额等信息:

+--------+---------------------+--------+--------+
| orderid| date | amount | price |
+--------+---------------------+--------+--------+
| 1 | 2022-04-01 09:00:00 | 1 | 28.99 |
| 2 | 2022-04-01 09:05:00 | 2 | 10.99 |
| 3 | 2022-04-01 09:15:00 | 1 | 65.99 |
| 4 | 2022-04-02 13:00:00 | 5 | 5.99 |
| 5 | 2022-04-02 13:36:00 | 3 | 19.99 |
| 6 | 2022-04-03 11:22:00 | 2 | 35.99 |
+--------+---------------------+--------+--------+

如果我们需要查询“orders”表中不同日期下的订单数量和金额之和,我们可以执行以下SQL语句:

SELECT date,SUM(amount),SUM(price)
FROM orders
GROUP BY date;

执行结果:

+---------------------+-------------+-------------+
| date | SUM(amount) | SUM(price) |
+---------------------+-------------+-------------+
| 2022-04-01 09:00:00 | 1 | 28.99 |
| 2022-04-01 09:05:00 | 2 | 10.99 |
| 2022-04-01 09:15:00 | 1 | 65.99 |
| 2022-04-02 13:00:00 | 5 | 5.99 |
| 2022-04-02 13:36:00 | 3 | 19.99 |
| 2022-04-03 11:22:00 | 2 | 35.99 |
+---------------------+-------------+-------------+

综上所述,使用distinct关键字和group by语句都可以实现MySQL去重不保留重复元组的需求。需要根据具体情况选择具体的方法来实现。


数据运维技术 » MySQL去重不保留重复元组(mysql不保留重复元祖)