我的查询无效
我有一张酒店餐桌 以及具有酒店ID作为外键的酒店评论表,并具有评论ID和评级栏。我想在酒店名单中列出前5家高评级酒店的酒店名称, 但是我一直在跟踪错误
#1241 - Operand should contain 1 column(s) when I try this query bellow
我的查询如下:
select hotel_id, hotel_name
from hotels
where hotel_id in (
SELECT hotel_id, AVG( rating )
FROM hotel_rev
GROUP BY hotel_id
ORDER BY AVG( rating ) DESC
)
另一个有效但未返回正确结果的查询
SELECT hotel_id ,hotel_name
FROM hotels
and hotel_id <> '".$_GET['hotel_id']."'
And city = '".$city."'
and hotel_id
IN (
SELECT hotel_id
FROM hotel_rev
GROUP BY hotel_id
ORDER BY AVG( rating ) DESC
)
LIMIT 4
有人可以帮助我吗?
答案 0 :(得分:0)
在第一个查询中,子查询返回两个值。试试这个:
select hotel_id, hotel_name
from hotels
where hotel_id in (SELECT hotel_id
FROM hotel_rev
GROUP BY hotel_id
ORDER BY AVG( rating ) DESC
)
但是,如果您只想要限制,请使用join
:
select h.hotel_id, h.hotel_name
from hotels h join
(select hotel_id
from hotel_rev
group by hotel_id
order by avg( rating ) desc
limit 5
) hr
on h.hotel_id = hr.hotel_id;
答案 1 :(得分:0)
您的第一个子查询只能返回hotel_id
,而不是平均值。如果您想将评分显示为列表的一部分,那么您可以将它们加入到一起,按酒店信息分组,并返回平均评分
SELECT h.hotel_id, h.hotel_name, AVG(hr.rating)
FROM hotels h
JOIN hotel_rev hr on hr.hotel_id = h.hotel_id
GROUP BY h.hotel_id, h.hotel_name
ORDER BY AVG(hr.rating) DESC
LIMIT 5