我有这个样本服务表,其中保存着我作为产品销售的按摩服务的记录。
||ID||Duration||Price||
|1 |100 |10.0|
|2 |200 |20.0|
|3 |300 |30.0|
|4 |400 |25.0|
|5 |500 |50.0|
加班,我添加比现有产品更具竞争力的新产品(价格和工期的组合)来吸引更多的客户。 我想查找过时的记录。当您需要多付少付时,它被认为已过时。在上面的示例中,ID为3的记录已过时。
如何编写查询来实现这一目标?
答案 0 :(得分:2)
过时的按摩是价格比持续时间更长的任何按摩
可以使用这种查询来检索过时的按摩:
SELECT m1.*
FROM massages m1
JOIN massages m2
ON m1.Price > m2.Price
AND m1.Duration <= m2.Duration
然后,该查询可用于在DELETE
查询中找到要删除的消息:
模式(MySQL v5.7)
CREATE TABLE massages (
`ID` INTEGER,
`Duration` INTEGER,
`Price` INTEGER
);
INSERT INTO massages
(`ID`, `Duration`, `Price`)
VALUES
(1, 100, 10.0),
(2, 200, 20.0),
(3, 300, 30.0),
(4, 400, 25.0),
(5, 500, 50.0);
-- -------------------------- This is what you are looking for --------------------------
DELETE FROM massages
WHERE massages.ID IN
(
SELECT id FROM
(
SELECT m1.ID AS id
FROM massages m1
JOIN massages m2
ON m1.Price > m2.Price
AND m1.Duration <= m2.Duration
) AS IdsToDelete
);
-- --------------------------------------------------------------------------------------
查询#1
SELECT * FROM massages;
输出
| ID | Duration | Price |
| --- | -------- | ----- |
| 1 | 100 | 10 |
| 2 | 200 | 20 |
| 4 | 400 | 25 |
| 5 | 500 | 50 |