30

我在 SO 上找到了一些主题,但我仍然找不到适合我的查询的设置。

这是查询,在 localhost 上效果很好:

@cars = Car.find_by_sql('SELECT cars.*, COUNT(cars.id) AS counter 
                         FROM cars 
                         LEFT JOIN users ON cars.id=users.car_id 
                         GROUP BY cars.id ORDER BY counter DESC')

但是在 Heroku 上给了我上面的错误 - GROUP BY 子句或在聚合函数中使用

然后我在某处读到,我应该指定表中的所有列,所以我尝试了这个:

@cars = Car.find_by_sql('SELECT cars.id, cars.name, cars.created_at, 
                                cars.updated_at, COUNT(cars.id) AS counter 
                         FROM cars 
                         LEFT JOIN users ON cars.id=users.car_id 
                         GROUP BY (cars.id, cars.name, cars.created_at, cars.updated_at) 
                         ORDER BY counter DESC')

但这不适用于本地主机,也不适用于 Heroku ......

查询的正确配置应该是什么?

4

3 回答 3

33

如果GROUPJOIN. _ 像这样:

SELECT id, name, created_at, updated_at, u.ct
FROM   cars c
LEFT   JOIN (
    SELECT car_id, count(*) AS ct
    FROM   users
    GROUP  BY 1
    ) u ON u.car_id  = c.id
ORDER  BY u.ct DESC;

这样,您需要的连接操作要少得多。并且表的行cars不必首先通过加入多个用户来相乘,然后再分组为唯一。
只需对正确的表进行分组,这也使逻辑更简单。

于 2012-04-16T00:01:54.843 回答
28

我认为您正在尝试在同一列上进行聚合和分组。这取决于你想要什么数据。以太这样做:

SELECT 
 cars.name, 
 cars.created_at, 
 cars.updated_at, 
 COUNT(cars.id) AS counter 
FROM cars 
LEFT JOIN users 
  ON cars.id=users.car_id 
GROUP BY cars.name, cars.created_at, cars.updated_at 
ORDER BY counter DESC

或者你想数一数?然后像这样:

SELECT
 cars.id,
 cars.name, 
 cars.created_at, 
 cars.updated_at, 
 COUNT(*) AS counter 
FROM cars 
LEFT JOIN users 
  ON cars.id=users.car_id 
GROUP BY cars.id, cars.name, cars.created_at, cars.updated_at 
ORDER BY counter DESC
于 2012-04-15T11:45:14.207 回答
8

您可以MAX()在汽车栏上使用技巧。

@cars = Car.find_by_sql('
SELECT cars.id, MAX(cars.name) as name, MAX(cars.created_at) AS 
created_at, MAX(cars.updated_at) as updated_at, COUNT(cars.id) AS counter 
FROM cars LEFT JOIN users ON cars.id=users.car_id 
GROUP BY cars.id ORDER BY counter DESC')
于 2012-04-15T11:51:42.197 回答