简体   繁体   中英

MySQL #1241 - Operand should contain 1 column(s)

I have this query not working

i have a hotels table and a hotel review table which has the hotel id as a foreign key and has review id and a rating column.

I wanted to list the hotel id with the hotel name for the top 5 high rated hotels , but I am getting following error all the time

 #1241 - Operand should contain 1 column(s) when I try this query bellow 

My query is as below:

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 
)

another query which working but not returning the correct results is bellow

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

Could any one help me please?

In your first query, the subquery is returning two values. Try this:

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 
                  )

However, if you only want a limit, use a 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;

Your first subquery can only return the hotel_id , not the average as well. If you want to show the rating as part of the listing then you can join them together, grouped by the hotel info, and return the average rating

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM