0

我有几个表,命名如下:

table_2012_12
table_2012_10
table_2012_07

两者具有相同的结构:

id
order_id
account_id

我知道我必须执行这些查询:

SELECT * FROM table_2012_12 where id=1
SELECT * FROM table_2012_12 where id=5  
SELECT * FROM table_2012_10 where id=1
SELECT * FROM table_2012_07 where id=22

使用单个查询的最佳(性能)方法是什么?

4

3 回答 3

1

操作员会这样做UNION。见:http ://dev.mysql.com/doc/refman/5.6/en/union.html

SELECT * FROM table_2012_12 where id=1
UNION ALL
SELECT * FROM table_2012_12 where id=5  
UNION ALL
SELECT * FROM table_2012_10 where id=1
UNION ALL
SELECT * FROM table_2012_07 where id=22

通常,您不应该只写UNION但是UNION ALL. UNION具有加入查询结果以及过滤掉任何重复行的效果。UNION ALL将简单地合并查询结果,并保留所有行。这效率更高

于 2012-10-21T08:01:43.310 回答
1

鉴于这种结构,您无法进行任何优化,但您可以进行联合查询:

SELECT * FROM table_2012_12 where id=1
UNION SELECT * FROM table_2012_12 where id=5  
UNION SELECT * FROM table_2012_10 where id=1
UNION SELECT * FROM table_2012_07 where id=22

UNION将自动删除重复项。

于 2012-10-21T08:02:15.823 回答
1
SELECT * FROM table_2012_12 where id=1 OR  id=5
UNION ALL SELECT * FROM table_2012_10 where id=1
UNION ALL SELECT * FROM table_2012_07 where id=22
于 2012-10-21T08:05:19.443 回答