我的这个mysql查询对每个选择都有限制,但我也想在整个查询中限制为1。我也试图围绕整个查询构建一个Select,但它仍然遍历所有表,即使第一个表中有结果,所以持续时间是相同的。我希望查询在得到结果后立即停止。对此有什么解决方案吗?
(SELECT count(*) FROM table1 i JOIN table1item it where it.columnId = 2 LIMIT 1)union
(SELECT count(*) FROM table2 i JOIN table2item it where it.columnId = 2 LIMIT 1)union
(SELECT count(*) FROM table3 i JOIN table3item it where it.columnId = 2 LIMIT 1)union
(SELECT count(*) FROM table4 i JOIN table4item it where it.columnId = 2 LIMIT 1)union
(SELECT count(*) FROM table5 i JOIN table5item it where it.columnId = 2 LIMIT 1)union
(SELECT count(*) FROM table6 i JOIN table6item it where it.columnId = 2 LIMIT 1)union
(SELECT count(*) FROM table7 i JOIN table7item it where it.columnId = 2 LIMIT 1)
答案 0 :(得分:2)
添加UNION ALL以确保如果它们相同,您将从所有表中获得结果。
(SELECT count(*) FROM table1 i JOIN table1item it where it.columnId = 2) UNION ALL
(SELECT count(*) FROM table2 i JOIN table2item it where it.columnId = 2) UNION ALL
(SELECT count(*) FROM table3 i JOIN table3item it where it.columnId = 2) UNION ALL
(SELECT count(*) FROM table4 i JOIN table4item it where it.columnId = 2) UNION ALL
(SELECT count(*) FROM table5 i JOIN table5item it where it.columnId = 2) UNION ALL
(SELECT count(*) FROM table6 i JOIN table6item it where it.columnId = 2) UNION ALL
(SELECT count(*) FROM table7 i JOIN table7item it where it.columnId = 2)
LIMIT 1
答案 1 :(得分:0)
一位同事发现了一个真正缩短查询时间的解决方案(在我的测试用例中为0.25而不是0.75):
SELECT
case
when count(*) > 0
then 1
else (
SELECT
case
when count(*) > 0
then 1
else (
SELECT
case
when count(*) > 0
then 1
else (
SELECT
case
when count(*) > 0
then 1
else (
SELECT
case
when count(*) > 0
then 1
else (
SELECT
case
when count(*) > 0
then 1
else (
SELECT
case
when count(*) > 0
then 1
else 0
end as result
FROM table1 i JOIN table1item it where it.fooId = 1 LIMIT 1
)
end as result
FROM table2 i JOIN table2item it where it.fooId = 1 LIMIT 1
)
end as result
FROM table3 i JOIN table3item it where it.fooId = 1 LIMIT 1
)
end as result
FROM table4 i JOIN table4item it where it.fooId = 1 LIMIT 1
)
end as result
FROM table5 i JOIN table5item it where it.fooId = 1 LIMIT 1
)
end as result
FROM table6 i JOIN table6item it where it.fooId = 1 LIMIT 1
)
end as result
FROM table7 i JOIN table7item it where it.fooId = 1 LIMIT 1