我必须从MySQL表中删除40万行。
我必须找到所有带输出的行 - &gt; &#34; 静态输出&#34; 然后删除上面输出的行并删除具有相同主机的下一行 以及<&gt; STATIC OUTPUT &#34;
以上输出和输出值的服务示例数据:
列 - &gt; ID,主机,服务,输出
1,"127.0.0.1","service1","STATIC OUTPUT"
2,"127.0.0.2","service5","RANDOM OUTPUT X0"
3,"127.0.0.2","service5","STATIC OUTPUT"
4,"127.0.0.3","service1","RANDOM OUTPUT X1"
5,"127.0.0.3","service10","RANDOM OUTPUT X2"
6,"127.0.0.2","service5","RANDOM OUTPUT X3"
7,"127.0.0.1","service2","RANDOM OUTPUT X4"
8,"127.0.0.1","service1","RANDOM OUTPUT X5"
9,"127.0.0.2","service4","RANDOM OUTPUT X6"
10,"127.0.0.3","service10","RANDOM OUTPUT X7"
11,"127.0.0.1","service1","RANDOM OUTPUT X7"
12,"127.0.0.1","service1","RANDOM OUTPUT X8"
13,"127.0.0.1","service1","RANDOM OUTPUT X9"
14,"127.0.0.2","service5","RANDOM OUTPUT X10"
15,"127.0.0.1","service1","STATIC OUTPUT"
16,"127.0.0.1","service1","RANDOM OUTPUT X11"
17,"127.0.0.1","service1","RANDOM OUTPUT X12"
...
示例:我们找到的时候
1,"127.0.0.1","service1","STATIC OUTPUT"
我们应该删除id值为1和8的行
8,"127.0.0.1","service1","RANDOM OUTPUT X5"
当我们找到
时3,"127.0.0.2","service5","STATIC OUTPUT"
我们应该删除id值为3和6的行
6,"127.0.0.2","service5","RANDOM OUTPUT X3"
我写了类似这样的东西(由于测试查询而导致DELETE语句的SELECT intead),
SELECT * FROM data r1 INNER JOIN (SELECT id, host, service
FROM data
WHERE output = 'STATIC OUTPUT') r2 ON
r1.id>r2.id AND r1.service=r2.service
AND r1.host=r2.host
AND r1.output<>'STATIC OUTPUT'
GROUP BY r1.host, r1.service
但我认为这是一种错误的方式。
MySQL 5.1.73
答案 0 :(得分:1)
CORRECTION
现在应该这样做!:
SELECT min(sp.id) as id FROM
(SELECT hs.id, hs.host, hs.service, hs.output, so.id as soid
FROM data hs
INNER JOIN
(SELECT id,host,service,output FROM data
WHERE output = "STATIC OUTPUT") so
ON so.host = hs.host and so.service = hs.service
AND hs.id > so.id WHERE hs.output <> "STATIC OUTPUT") sp
group by host,service, soid
UNION
SELECT id FROM data WHERE output = "STATIC OUTPUT";
答案 1 :(得分:-1)
您可以使用LIMIT语句选择第一个匹配项。 https://dev.mysql.com/doc/refman/5.7/en/select.html
SELECT * FROM data LIMIT 1;
此示例将为您找到要删除的ID
CREATE OR REPLACE VIEW v AS SELECT r1.id as id1 , r2.id as id2 FROM data r1 INNER JOIN data r2 ON r1.host=r2.host AND r1.service = r2.service WHERE LOWER(r1.output) LIKE "static output" AND r1.id < r2.id;
SELECT DISTINCT id1 FROM v UNION SELECT DISTINCT id2 FROM v;
id:1 3 6 8