如何合并这两个MySQL Select查询?

时间:2014-03-21 13:55:50

标签: mysql sql

我想将2个MySQL查询合并为2,因为性能会有所提高。基本上我喜欢在2个表中搜索元素的查询。如果它没有在一个中找到,它应该在另一个中搜索。这就是我创建2个查询的原因,但我确信它在日志运行中会比1个查询慢。

我有以下两个问题:

SELECT a_id FROM table1 WHERE name = 'George'
SELECT b_id FROM table2 WHERE name = 'George'

如何创建这些查询?它应该只返回找到匹配的1个id。

2 个答案:

答案 0 :(得分:2)

您可以使用UNION ALL查询:

SELECT a_id FROM table1 WHERE name = 'George'
UNION ALL
SELECT b_id FROM table2
WHERE
  name = 'George'
  AND NOT EXISTS (SELECT a_id FROM table1 WHERE name = 'George')

或者这个:

SELECT a_id, 1 as t FROM table1 WHERE name = 'George'
UNION ALL
SELECT b_id, 2 as t FROM table2 WHERE name = 'George'
ORDER BY t
LIMIT 1

但我认为它不会比运行两个单独的查询更快。

答案 1 :(得分:2)

尝试使用COALESCE

SELECT COALESCE(a_id,
       (SELECT b_id FROM table2 WHERE name = 'George'))
FROM table1 WHERE name = 'George'