如何在mysql中连接两个表

时间:2013-09-05 04:39:25

标签: mysql full-outer-join

我有一个income表,如下所示:

date              income      
---------------------------
09/05/13          56000    
09/05/13          66600
09/05/13          50000

一个expense表,如下所示:

date              expense 
----------------------------
09/05/13          68800

我想编写一个输出如下的查询:

date              income             expense 
---------------------------------------------
09/05/13          56000              68800
09/05/13          66600
09/05/13          50000

1 个答案:

答案 0 :(得分:3)

UPDATE2:如果您不关心收入值与费用值匹配的特定订单,您可以通过此类查询获得所需的输出

SELECT date, 
       MAX(CASE WHEN type = 1 THEN amount END) income,
       MAX(CASE WHEN type = 2 THEN amount END) expense
  FROM
(
  SELECT 1 type, date, income amount, @n := IF(@g = date, @n + 1, 1) rnum, @g := date g
    FROM income CROSS JOIN (SELECT @n := 0, @g := NULL) i1
   UNION ALL
  SELECT 2, date, expense amount, @m := IF(@f = date, @m + 1, 1) rnum, @f := date g
    FROM expense CROSS JOIN (SELECT @m := 0, @f := NULL) i2
) q
 GROUP BY date, rnum

输出:

|               DATE | INCOME | EXPENSE |
|--------------------|--------|---------|
| September, 05 2013 |  56000 |   68800 |
| September, 05 2013 |  66600 |  (null) |
| September, 05 2013 |  50000 |  (null) |

这是 SQLFiddle 演示


UPDATE1:使用像

这样的查询对每日收入和费用进行分组似乎合乎逻辑
SELECT a.date, i.income, e.expense
  FROM
(
  SELECT date
    FROM income
  UNION
  SELECT date
    FROM expense 
) a LEFT JOIN 
(
  SELECT date, SUM(income) income
    FROM income
   GROUP BY date
) i
    ON a.date = i.date LEFT JOIN 
(
  SELECT date, SUM(expense) expense
    FROM expense
   GROUP BY date
) e
    ON a.date = e.date

输出:

|               DATE | INCOME | EXPENSE |
|--------------------|--------|---------|
| September, 05 2013 | 172600 |   68800 |

这是 SQLFiddle 演示


原始问题的原始答案:如果您需要原始问题中所述的FULL OUTER JOIN(超过date列),那么这样就可以了

SELECT a.date, i.income, e.expense
  FROM
(
  SELECT date
    FROM income
  UNION
  SELECT date
    FROM expense 
) a LEFT JOIN income i
    ON a.date = i.date LEFT JOIN expense e
    ON a.date = e.date

但是你会得到这个作为输出

|          DATE | INCOME | EXPENSE |
|---------------|--------|---------|
| September, 05 |  56000 |   68800 |
| September, 05 |  66600 |   68800 |
| September, 05 |  50000 |   68800 |

这是 SQLFiddle 演示