我在查询数据库类时遇到了一些困难。给出以下架构:
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)
问题来自我想重命名表的方式。我想使用预订和房间的自然连接作为笛卡尔产品的组件...我该怎么做?
非常感谢。
答案 0 :(得分: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
,因此您有两个客户:
(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