我有一个表(价格),有两个字段,代码(字符)和价格(十进制)。我需要查找所有具有相同代码的记录,价格低于或低于两个最高价格。
E.G。在这种情况下,我希望删除id = 1:
id code price
1 1001 10
2 1001 101
3 1001 40
4 1001 201
5 1002 122
6 1002 50
答案 0 :(得分:2)
DELETE
FROM myTable
WHERE ID IN (
SELECT *
FROM (
SELECT t2.id
FROM myTable t2
WHERE EXISTS (
SELECT 1
FROM myTable t3
WHERE t3.code = t2.code
AND t3.price > t2.price * 5
HAVING COUNT(*) > 1
)
) t
)
;
答案 1 :(得分:1)
我的方法:
DELETE t
FROM t
JOIN (SELECT code,
REVERSE(SUBSTRING_INDEX(REVERSE(SUBSTRING_INDEX(
GROUP_CONCAT(price ORDER BY price DESC SEPARATOR ';'), ';', 2)), ';',1))
AS second_price
FROM t
GROUP BY code) s
ON t.code = s.code
AND t.price * 5 < s.second_price;
<强> Rextester Demo 强>
它基于选择第二价格:
SELECT code,
REVERSE(SUBSTRING_INDEX(REVERSE(SUBSTRING_INDEX(
GROUP_CONCAT(price ORDER BY price DESC SEPARATOR ';'), ';', 2)), ';',1))
AS second_price
FROM t
GROUP BY code;
<强> Rextester Demo2 强>
修改强>
实际上它可能更容易:
DELETE t
FROM t
JOIN (SELECT code,
SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(price ORDER BY price DESC SEPARATOR ';'),
';', 2), ';',-1) AS second_price
FROM t
GROUP BY code) s
ON t.code = s.code
AND t.price * 5 < s.second_price;
<强> Rextester Demo 强>
良好而快速的解决方案,但老实说,我无法清楚地理解它。
很容易理解:
SELECT code,
GROUP_CONCAT(price ORDER BY price DESC SEPARATOR ';'),
SUBSTRING_INDEX(GROUP_CONCAT(price ORDER BY price DESC SEPARATOR ';'), ';', 2),
SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(price ORDER BY price DESC SEPARATOR ';'),
';', 2), ';',-1)
FROM t
GROUP BY code;