首先,好消息:我只有一张桌子。
现在,我有3个类似的查询:
SELECT id FROM (
SELECT * FROM my_table
ORDER BY columnA
DESC LIMIT 600
) AS aliasA
WHERE (revenue > 10000);
SELECT id FROM (
SELECT * FROM my_table
ORDER BY columnB
DESC LIMIT 400, 999999999999
) AS aliasB
WHERE (revenue > 10000);
SELECT id FROM (
SELECT * FROM my_table
ORDER BY columnC
DESC LIMIT 800;
) AS aliasC
WHERE (revenue > 10000);
注意WHERE子句是相同的。
有没有办法组合这3个查询,以便我可以从3个子查询的交集中搜索(查找匹配所有3个子查询的行,以及我的WHERE子句)?
顺便说一句,如果我的单个查询(合并之前)可以简化,请告诉我。
谢谢!
答案 0 :(得分:1)
SELECT ID FROM
(SELECT id FROM (
SELECT *
FROM my_table
WHERE (revenue > 10000)
ORDER BY columnA DESC
LIMIT 600
) AS aliasA) AS a
INNER JOIN (
SELECT id FROM (
SELECT *
FROM my_table
WHERE (revenue > 10000)
ORDER BY columnB DESC
LIMIT 400, 999999999999
) AS aliasB
)
AS b ON a.id = b.id
INNER JOIN (
SELECT id FROM (
SELECT *
FROM my_table
WHERE (revenue > 10000)
ORDER BY columnC DESC
LIMIT 800
) AS aliasC
)
AS c ON a.id = c.id AND b.id = c.id
然后你可以搜索这个查询
答案 1 :(得分:0)
您可以在key:id上使用INNER JOIN,然后将where子句放在最后。所有3个查询都在使用收入> 10000,它可以组合在onenwhere子句中,因为所有收入列都来自同一个表。
select t1.id from (
SELECT id, revenue FROM (
SELECT * FROM my_table
ORDER BY columnA
DESC LIMIT 600
) AS aliasA) as t1
INNER JOIN (
SELECT id FROM (
SELECT * FROM my_table
ORDER BY columnB
DESC LIMIT 400, 999999999999
) AS aliasB) as t2 on t1.id= t2.id
INNER JOIN (
SELECT id, revenue FROM (
SELECT * FROM my_table
ORDER BY columnC
DESC LIMIT 800;
) AS aliasC) as t3 on t1.id =t3.id
WHERE (t1.revenue > 10000);
答案 2 :(得分:0)
在您的情况下,最佳解决方案是JOIN USING(id):
sudo chown root:root ~/.aws
如果您的子查询中没有LIMIT,则可以使用id IN:
SELECT id
FROM (SELECT id FROM my_table ORDER BY columnA DESC LIMIT 600)
aliasA
JOIN (SELECT id FROM my_table ORDER BY columnB DESC LIMIT 400, 999999999999)
aliasB USING (id)
JOIN (SELECT id FROM my_table ORDER BY columnC DESC LIMIT 800)
aliasC USING (id)
JOIN my_table USING (id)
WHERE (revenue > 10000);
但子查询中不支持LIMIT,因此您无法执行此操作。
如果您使用的是其他SQL,则可以使用INTERSECT:
SELECT id FROM my_table
WHERE (
id IN (SELECT id FROM my_table ORDER BY columnA DESC LIMIT 600)
AND
id IN (SELECT id FROM my_table ORDER BY columnB DESC LIMIT 400, 999999999999)
AND
id IN (SELECT id FROM my_table ORDER BY columnC DESC LIMIT 800)
AND
revenue > 10000
)
然而,MySql不支持INTERSECT。