mysql> describe events;
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| city_id | int(11) | NO | MUL | NULL | |
以下sql导致错误。
SELECT CONCAT_WS('',users.fname,' ', users.lname) as user_name,
COUNT(events.id) AS events_count
FROM users
INNER JOIN events ON users.id = events.user_id
INNER JOIN cities ON cities.id = events.city_id
GROUP BY
users.id
WHERE
events.city_id = 18
ORDER BY
COUNT(events.id) DESC
LIMIT 10
错误
ActiveRecord::StatementInvalid: Mysql2::Error: 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 'WHERE
events.city_id = 18
如果我删除了WHERE子句,那么一切正常。
答案 0 :(得分:3)
尝试将WHERE
子句放在GROUP BY
答案 1 :(得分:2)
在GROUP BY之前使用WHERE,它应该可以工作
答案 2 :(得分:2)
WHERE
需要在GROUP BY
答案 3 :(得分:1)
将events.city_id=18
条件放入JOIN中。因为你正在进行INNER连接,所以没有理由在WHERE子句中使用它。
INNER JOIN events ON users.id = events.user_id AND events.city_id=18
答案 4 :(得分:0)
您的意思是使用GROUP BY...HAVING
吗?