从其他子查询中向mysql查询添加一列

时间:2013-09-10 18:33:09

标签: php mysql sql

我有一张表user(id,name)和一张表payments(date,amount,user_id)

我需要一个查询,以便为每个用户显示上个月的付款总额和付款。

User - totalpayments - monthlypayments

类似这样的事情

  1. SELECT id, name from user;
  2. SELECT COUNT(amount) FROM payments WHERE user_id=user.id;
  3. SELECT COUNT(amount) FROM payments WHERE user_id=user.id AND (data<=$timestamptoday AND data>=$timestamp1stday)
  4. 可以在不做多次查询的情况下做到这一点吗?

2 个答案:

答案 0 :(得分:2)

当然,您可以在一个查询中执行此操作。

SELECT
    u.ID,
    u.Name,
    SUM(p.amount),
    SUM(CASE
          WHEN p.date <= '2013-02-01' AND p.date >= '2013-01-01' THEN p.amount
          ELSE 0
        END)
FROM
    Users u
JOIN
    Payments p ON u.ID = p.UserID
GROUP BY
    u.ID,
    u.Name

工作DEMO

答案 1 :(得分:0)

绝对可以将其作为单个查询执行:

SELECT    user.name, SUM(amount) AS totalpayments, SUM(IF(date <= '$enddate' AND date >= '$startdate'),amount,0) AS monthlypayments
FROM      user LEFT JOIN payments ON user.id = payments.user_id
GROUP BY  user.id
ORDER BY  user.name ASC

请注意,我假设您正在查找付款总额,而不是付款次数,我使用SUM而不是COUNT