1

我在查询我的数据库类时遇到了一些困难。给定以下架构:

  • 客户 ( customerid, first_name, last_name, address, city, state, phone, status)
  • 分支机构 ( branchno, address, city, state, phone, manager_name)
  • 员工 ( empno, firstname, lastname, address, city, state, phone, emergency_contact, title, managerno)
  • 房间 ( roomno, branchno, price, bed_size)
  • 预订 ( roomno, branchno, customerid, checkin_date, checkout_date, empno)

我想找到租了最贵房间的客户。我试了一下这个查询......

SELECT customerid FROM bookings NATURAL JOIN rooms 
EXCEPT
(SELECT customerid FROM (bookings NATURAL JOIN rooms) AS S, (bookings NATURAL JOIN
    rooms) as T WHERE S.price < T.price)

问题来自我想重命名表的方式。我想使用预订和房间的自然连接作为笛卡尔积的组成部分......我该怎么做?

非常感谢。

4

2 回答 2

2

你可以使用这个:

SELECT 
    customerid 
FROM 
    Bookings 
  NATURAL JOIN 
    Rooms
  NATURAL JOIN
    ( SELECT MAX(price) AS price
      FROM Rooms
    ) AS MostExpensiveRoom

您的查询似乎有效,除了您需要customerid在第二个子查询中阐明您想要的那个S.或那个T.。逗号,语法表示CROSS JOIN介于S和之间,T因此您有两个客户 ID:

(SELECT customerid FROM bookings NATURAL JOIN rooms)
EXCEPT
(SELECT S.customerid 
 FROM 
     (bookings NATURAL JOIN rooms) AS S
   CROSS JOIN
     (bookings NATURAL JOIN rooms) AS T 
 WHERE S.price < T.price
)
于 2011-12-12T00:40:40.497 回答
-1
SELECT * FROM customers as c
INNER JOIN bookings as b ON b.customerid = c.customerid
INNER JOIN rooms as r ON r.roomno = b.roomno
ORDER BY r.price DESC
LIMIT 1;

如果您只需要名称或指定字段,则可以使用 GROUP BY。

这个查询做同样的事情(如果前一个在语法上很好):

SELECT * FROM customers,bookings,rooms
WHERE bookings.customerid = customers.customerid
AND rooms.roomno = bookings.roomno
ORDER BY rooms.price DESC
LIMIT 1

因此,如果您想要按租金价格降序排列的 id-s 和名称:

SELECT customers.customerid, customers.fistname, customers.lastname FROM
customers,bookings,rooms
WHERE bookings.customerid = customers.customerid
AND rooms.roomno = bookings.roomno
ORDER BY rooms.price DESC
GROUP BY customers.customerid, customers.fistname, customers.lastname 
LIMIT 10
于 2011-12-12T00:49:25.837 回答