MySQL SELECT子查询

时间:2014-08-20 03:58:18

标签: mysql select join subquery

我有一个calendar和user_result表,我需要加入这两个查询。

日历查询

SELECT `week`, `date`, `time`, COUNT(*) as count
FROM `calendar` 
WHERE `week` = 1
GROUP BY `date`
ORDER BY `date` DESC

,结果是

{"week":"1","date":"2014-08-21","time":"15:30:00","count":"4"}, {"week":"1","date":"2014-08-20","time":"17:30:00","count":"12"}

user_result查询

SELECT `date`, SUM(`point`) as score
FROM `user_result` 
WHERE `user_id` = 1
AND `date` = '2014-08-20'

,结果只是得分3

我的目标是即使用户不在user_result表格中,也始终显示日历,但如果他在,则为calendar.date = user_result.date当天的点数。结果应该是:

{"week":"1","date":"2014-08-21","time":"15:30:00","count":"4","score":"3"}, {"week":"1","date":"2014-08-20","time":"17:30:00","count":"12","score":"0"}

我在下面尝试了这个查询,但结果只有一行和意外的计数

SELECT c.`week`, c.`date`, c.`time`, COUNT(*) as count, SUM(p.`point`) as score
FROM `calendar` c
INNER JOIN `user_result` p ON c.`date` = p.`date`
WHERE c.`week` = 1
AND p.`user_id` = 1
GROUP BY c.`date`
ORDER BY c.`date` DESC

{"week":"1","date":"2014-08-20","time":"17:30:00","count":"4","score":"9"}

SQL Fiddle

2 个答案:

答案 0 :(得分:1)

对不起,我被编辑了,我尝试了你的sqlfiddle,如果你想显示日历中的所有日期你可以使用LEFT JOIN,但是如果你想在日历和结果之间显示相同的日期你可以使用INNER JOIN,注意:在这种情况下,INNER JOIN只显示1个结果,而LEFT JOIN显示2个结果

    SELECT c.`week`, p.user_id, c.`date`, c.`time`, COUNT(*) as count, p.score 
    FROM `calendar` c
    LEFT JOIN 
    (
      SELECT `date`, SUM(`point`) score, user_id
      FROM `result` 
      group by `date`
    ) p ON c.`date` = p.`date`

    WHERE c.`week` = 1
    GROUP BY c.`date`
    ORDER BY c.`date` DESC

答案 1 :(得分:0)

我将一个预先聚合的查询/按日期分组作为您感兴趣的一个人的选择......然后对其进行左连接。此外,您的列名称周,日期和时间(IMO)是糟糕的选择列名称,因为它们在MySQL中看起来太接近reserved keywords。它们不是,但可能令人困惑......

SELECT
      c.week,
      c.date,
      c.time,
      coalesce( OnePerson.PointEntries, 0 ) as count,
      coalesce( OnePerson.totPoints, 0 ) as score
   FROM
      calendar c
         LEFT JOIN ( select
                           r.week,
                           r.date,
                           COUNT(*) as PointEntries,
                           SUM( r.point ) as totPoints 
                        from
                           result r
                        where
                               r.week = 1
                           AND r.user_id = 1
                        group by
                           r.week,
                           r.date ) OnePerson
            ON  c.week = OnePerson.week
            AND c.date = OnePerson.date
   WHERE 
      c.week = 1
   GROUP BY 
      c.date 
   ORDER BY 
      c.date DESC 

将代码发布到SQLFiddle