这里的逻辑错误是输出显示如下:
+-----------------+-------+----------+-------+
| registration_no | color | producer | count |
+-----------------+-------+----------+-------+
| X23-234 | green | VW | 2 |
| BC-343 | red | BMW | 2 |
| TW-435 | blue | Ford | 1 |
| 232-444 | pink | Army | 2 |
+-----------------+-------+----------+-------+
正如您所看到的,最小计数是蓝色,我希望它只显示:
| TW-435 | blue | Ford |
派生查询不应仅限制关键字嵌套查询。 这是我的SQL查询:
mysql> SELECT registration_no, color, producer, COUNT(*) as count
FROM car, car_type, booking
WHERE car.car_type_id = car_type.car_type_id and booking.car_id = car.car_id
GROUP BY car.car_id;
我无法找出解决方案。
答案 0 :(得分:0)
按计数(*)排序,然后在第一行限制
SELECT registration_no, color, producer, COUNT(*) as count
FROM car, car_type, booking
WHERE car.car_type_id = car_type.car_type_id and booking.car_id =car.car_id
GROUP BY car.car_id
ORDER BY COUNT(*) ASC
LIMIT 1;
如果你只想要一行,这是有效的。如果你有更多行count(*) = 1
,那么你应该使用另一种方法
如果你想显示最高计数只是排序降序
....
ORDER BY COUNT(*) DESC
但在这种情况下,您将获得3行count = 2
中的一行,而不是所有三行
答案 1 :(得分:0)
按计数排序,只使用limit
SELECT registration_no, color, producer, COUNT(*) as count
FROM car
join car_type on car.car_type_id = car_type.car_type_id
JOIN booking on booking.car_id = car.car_id
GROUP BY car.car_id
order by count asc
limit 1
BTW使用显式连接语法。
答案 2 :(得分:0)
我认为您需要这样的查询:
SELECT registration_no, color, producer
FROM (
SELECT registration_no, color, producer, COUNT(*) as count
FROM car, car_type, booking
WHERE car.car_type_id = car_type.car_type_id and booking.car_id = car.car_id
GROUP BY car.car_id) DT
ORDER BY count
LIMIT 1;
答案 3 :(得分:0)
您可以使用此查询来选择最小计数:
select min(count) from (select COUNT(*) as count
FROM car, car_type, booking
WHERE car.car_type_id = car_type.car_type_id and booking.car_id = car.car_id
GROUP BY car.car_id);
答案 4 :(得分:0)
mysql> SELECT registration_no, color, producer
FROM car, car_type, booking
WHERE car.car_type_id = car_type.car_type_id and booking.car_id =car.car_id
GROUP BY car.car_id
ORDER BY COUNT(*) ASC
LIMIT 1;
+-----------------+-------+----------+
| registration_no | color | producer |
+-----------------+-------+----------+
| TW-435 | blue | Ford |
+-----------------+-------+----------+
1 row in set