SQL查询问题 - 自然连接和表命名

时间:2011-12-12 00:31:16

标签: sql join natural-join

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

  • 客户(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)

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

非常感谢。

2 个答案:

答案 0 :(得分:2)

你可以用这个:

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

您的查询似乎有效,但您需要在第二个子查询,customeridS.中明确说明您想要的T.。逗号,语法表示CROSS JOINS之间的T,因此您有两个客户:

(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
)

答案 1 :(得分:-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

所以如果你想要以租金价格desc命令的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