SQL Query连接两个表

时间:2013-04-30 10:59:40

标签: mysql sql

我有两张表如下: -

 table1                                table2
 date      time  amount                date      time amount
 20120101  1000   101                  20120104  1000   10
 20120101  1100   100                  20120104  1100   11
 20120104  1000   101                  20120105  1000   11
 20120104  1100   105                  20120105  1100   8 

我想加入这两个表来获取输出,如下所示:

 date      time  table1-amt   table2-amt
 20120101  1000   101          NULL
 20120101  1100   100          NULL
 20120104  1000   101           10
 20120104  1100   105           11
 20120105  1000   NULL          11
 20120105  1100   NULL          8

获取此输出的sql查询是什么?我正在使用mysql数据库。

我尝试了以下查询:

  select table1.date,table1.time,table1.close , table2.close 
  from table1,
        table2 
  where table1.date=table2.date 
  and table1.time=table2.time;

它给了我输出

    date       time  amount       amount
    20120104   1000   101           10
    20120104   1100   105           11

人们指引我走向左外连接,完全外连接我尝试了两个查询,但没有解决我的目的。

   select * from table1 left join table2 on table1.date=table2.date ;

  select * from table1 left join table2 on table1.date=table2.date union select * from table1 right join table2 on table1.date=table2.date;

3 个答案:

答案 0 :(得分:2)

只涉及从每个表中读取一次的方法:

SELECT `date`, `time`, sum(`amt1`) as `table1-amt`, sum(`amt2`) as `table2-amt` 
FROM
(SELECT `date`, `time`, amount as amt1, null as amt2
 FROM Table1
 UNION ALL
 SELECT  `date`, `time`, null as am1, amount as amt2
 FROM Table2) v
GROUP BY `date`, `time`

(与Yordi的答案中链接的示例相反,每次从每个表中读取两次。)

答案 1 :(得分:1)

这就是你想要的

Full Outer Join in MySQL

不会只是给出答案,你会在那里找到并学习一些。

编辑:哦,有人打败我,然后把它递给你^^。

答案 2 :(得分:0)

您需要FULL(外部)JOIN。在MySQL中实现它的一种方法:

SELECT t1.date, t1.time, t1.close AS table1_amt, t2.close AS table2_amt 
FROM table1 AS t1
  LEFT JOIN table2 AS t2
    ON  t1.date = t2.date 
    AND t1.time = t2.time

UNION ALL

SELECT t2.date, t2.time, t1.close, t2.close 
FROM table1 AS t1
  RIGHT JOIN table2 AS t2
    ON  t1.date = t2.date 
    AND t1.time = t2.time
WHERE t1.date IS NULL ;