具有相同列的SQL连接表

时间:2012-05-28 14:44:57

标签: mysql datetime date date-range

我环顾四周,找不到答案。可能是我不知道正确的术语。

我有大约15个表,都有相同的列和类似的数据。它们之间的唯一区别是创建日期。

我想像这样搜索其中一些:

SELECT * 
FROM table_2010, table_2011 
WHERE date_created BETWEEN '2010-04-01' AND '2011-04-01'
ORDER BY date_created

但我不相信这会有效,因为它会将我的所有数据都视为2个表,并创建不明确的字段:P

有什么建议吗?这是工会工作还是什么?!

6 个答案:

答案 0 :(得分:1)

创建表对象,试试这个

SELECT * 
FROM table_2010 AS t1, table_2011 AS t2
WHERE ( t1.date_created BETWEEN '2010-04-01' AND '2011-04-01' AND t2.date_created BETWEEN '2010-04-01' AND '2011-04-01')
ORDER BY t1.date_created,t2.date_created

答案 1 :(得分:1)

select * 
from (SELECT * FROM table_2010
      WHERE date_created BETWEEN '2010-04-01' AND '2011-04-01'
      union
      SELECT * FROM table_2011
      WHERE date_created BETWEEN '2010-04-01' AND '2011-04-01'
) as t
ORDER BY date_created

答案 2 :(得分:0)

使用别名'

SELECT * 
FROM table_2010 as t2010, table_2011 as t2011 
WHERE t2010.date_created BETWEEN '2010-04-01' AND '2011-04-01'
ORDER BY t2010.date_created

答案 3 :(得分:0)

试试这个

SELECT table_2010.*, table_2011.* 
FROM table_2010, table_2011 
WHERE table_2010.date_created >= '2010-04-01' AND table_2011.date_created <= '2011-04-01'
ORDER BY table_2010.date_created, table_2011.date_created

我相信在2010年表中您只有2010年的数据而且2011年表只有2011年的数据。

答案 4 :(得分:0)

SELECT *  FROM table_2010 
WHERE date_created BETWEEN '2010-04-01' AND '2011-04-01' ORDER BY date_created 

union

SELECT *  FROM table_2011 
WHERE date_created BETWEEN '2010-04-01' AND '2011-04-01' ORDER BY date_created 

答案 5 :(得分:0)

这是一个联盟,但您需要从联盟中选择以获取跨表的顺序,但如果date_created始终在表的年份中,您可能可以跳过该步骤

Select * From (
SELECT *  FROM table_2010
WHERE date_created BETWEEN '2010-04-01' AND '2011-04-01'
Union all
Select * From Table_2010
WHERE date_created BETWEEN '2010-04-01' AND '2011-04-01'
) allmyTables
ORDER BY date_created