多个表上的MySQL子查询

时间:2014-05-02 07:00:42

标签: mysql sql

我正在尝试检索伦敦一家酒店的所有客人的姓名和地址,在MySQL中使用子查询按名称按字母顺序排序并收到此错误:

Error Code: 1242. Subquery returns more than 1 row

这是我运行的查询:

select * from guest 
where guest_no = 
    (
        select guest_no 
        from booking 
        where hotel_no = (select hotel_no
                          from hotel
                          where city = 'London')
    );

以及酒店,预订和客人的架构:

hotel (hotel_no, hotel_name, city)

booking (hotel_no, guest_no, date_from, date_to, room_no)

guest (guest_no, g_name, g_address)

另外,这里是房间的架构:

room (room_no, hotel_no, type, price)

请帮助我解决上述错误和可能的解决方案。

谢谢和问候。

4 个答案:

答案 0 :(得分:2)

为什么不使用join作为

select
g.guest_no,
g.g_name,
g.g_address
from guest g
inner join booking b on b.guest_no = g.guest_no
inner join hotel h on h.hotel_no = b.hotel_no
where h.city = 'London'

答案 1 :(得分:0)

使用'='时,表示子查询的结果正好是1行。如果您希望获得多个结果,则需要使用IN关键字,如下所示:

select * from guest where guest_no IN (select guest_no from booking where hotel_no IN (select hotel_no from hotel where city = 'London'));

编辑:正如@flaschenpost所提到的,如果子查询中涉及的列没有正确的索引,性能可能会降低。您可能最好使用JOIN而不是这样的嵌套子查询。

答案 2 :(得分:0)

将查询更改为

select * from guest 
where guest_no IN 
               (select guest_no from booking where hotel_no 
  IN (select hotel_no from hotel where city = 'London'));

答案 3 :(得分:0)

你需要加入!

试试这个!

select a.g_name,a.g_address from guest a inner join booking b on a.guest_no=b.guest_number inner join hotel h on b.hotel_no=h.hotel_no inner join rooms r on b.room_no=h.room_no
where h.city='London'