如何从MYSQL中的2个表中获取数据

时间:2012-08-30 03:25:53

标签: mysql database join left-join

假设我有2个表:成员和订单(Mysql)

Members : 
id   |   name
1    |   Lee
2    |   brad
Orders : 
id   |   member_id   |   status (1: paid, 2: unpaid)   |    total
1    |   1           |   1                             |   1000000 
2    |   1           |   1                             |   1500000
3    |   1           |   2                             |   1300000
4    |   2           |   1                             |   3000000 
5    |   2           |   2                             |   3500000
6    |   2           |   2                             |   3300000

我有一个SQL查询:

SELECT m.name,
       o.member_id,
       COUNT(o.id)  AS number_of_order,
       SUM(o.total) AS total2
FROM   orders o
       LEFT JOIN members m
              ON o.member_id = m.id
GROUP  BY o.member_id

给我这个:

name   |   number_of_order   |   total2
Lee    |   3                 |   3800000
brad   |   3                 |   9800000

我想要的就是这样:

    name   |   number_of_order   |   total2
           |  Paid        Unpaid | Paid      Unpaid
    ------------------------------------------------
    Lee    |         3           |   3800000
           |  2             1    | 2500000   1300000
    ------------------------------------------------
    brad   |         3           |   9800000
           |  1             2    | 3000000   6800000
    ------------------------------------------------

如何进行可以给我结果的查询?

谢谢你的时间!

2 个答案:

答案 0 :(得分:4)

您可以使用SUM/COUNT函数中的条件。

SELECT 
  m.name,
  COUNT(o.id) AS number_of_order,
  SUM(o.total) AS total2,
  COUNT(IF(o.status=1, 1, NULL)) AS paid_order,
  COUNT(IF(o.status=2, 1, NULL)) AS unpaid_order,
  SUM(IF(o.status=1, o.total, 0)) AS paid,
  SUM(IF(o.status=2, o.total, 0)) AS unpaid
FROM orders o 
LEFT JOIN members m ON o.member_id=m.id
GROUP BY o.member_id

答案 1 :(得分:0)

尝试使用不同的别名和where子句多次列出orders表。类似的东西:

SELECT m.name,
       COUNT(po.id),
       COUNT(uo.id),
       COUNT(o.id),
       SUM(po.total),
       SUM(uo.total),
       SUM(o.total)
FROM   members m,
       orders o,
       orders po,
       orders uo
WHERE  o.member_id = m.id
       AND po.member_id = m.id
       AND uo.member_id = m.id
       AND po.status = 1
       AND uo.status = 2
GROUP  BY m.name

这不完全是你所要求的,但它应该让你朝着正确的方向前进。