MySQL - LEFT JOIN中的错误#1064

时间:2017-12-04 12:23:38

标签: mysql join left-join

我目前正在尝试仅使用MySQL查询格式化数据。我不想使用编程语言来操纵它。所有操作仅在一个表上完成。

这是我的问题:

    SELECT DATE(datetime_column) AS date, COUNT(`id`) AS users_a FROM users a 
    WHERE datetime_column >= '2017-12-01' GROUP BY DATE(datetime_column), rank HAVING rank = "good"

    LEFT JOIN (SELECT DATE(datetime_column) AS date, COUNT(`id`) AS users_b FROM users
    WHERE datetime_column >= '2017-12-01' GROUP BY DATE(datetime_column), rank HAVING rank = "bad") AS b 
    ON b.date = a.date;

输出应该是:

date           users_a           users_b
2017-12-01     17                20
2017-12-02     4                 9

如果两个查询分别执行,那么这两个查询会给出准确的结果,我只希望数据在一个表中。但是,我收到以下错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN (SELECT DATE(datetime) AS date, COUNT(`id`) AS users_b FROM ' at line 2 

2 个答案:

答案 0 :(得分:0)

试试这个

SELECT DATE(datetime_column) date, SUM(CASE WHEN rank = "good" THEN 1 END) users_a, SUM(CASE WHEN rank = "bad" THEN 1 END) users_b
FROM users
WHERE datetime_column>= '2017-12-01'
GROUP BY DATE(datetime_column)

答案 1 :(得分:0)

JOINs必须出现在HAVING子句之前。

根据MySQL SELECT documentation

SELECT
    [ALL | DISTINCT | DISTINCTROW ]
      [HIGH_PRIORITY]
      [STRAIGHT_JOIN]
      [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
      [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
    select_expr [, select_expr ...]
    [FROM table_references
      [PARTITION partition_list]
    [WHERE where_condition]
    [GROUP BY {col_name | expr | position}
      [ASC | DESC], ... [WITH ROLLUP]]
    [HAVING where_condition]
    [ORDER BY {col_name | expr | position}
      [ASC | DESC], ...]
    [LIMIT {[offset,] row_count | row_count OFFSET offset}]
    [PROCEDURE procedure_name(argument_list)]
    [INTO OUTFILE 'file_name'
        [CHARACTER SET charset_name]
        export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]
    [FOR UPDATE | LOCK IN SHARE MODE]]

另外,您还可以将其简化为:

SELECT
    DATE(`datetime_column`) AS `date`, 
    SUM(IF(`rank` = 'good', 1, 0)) AS `users_a`,
    SUM(IF(`rank` = 'bad', 1, 0)) AS `users_b`
FROM
    `users`
WHERE
   datetime_column >= '2017-12-01'
GROUP BY
    DATE(datetime_column)

为每个'好的'增加users_a列。用户,users_b为每个'坏'。