这是使用Oracle SQL。
编辑了我的代码,我把它贴错了。
所以我有两个表:class和event。每个类都有一个class_id,它也存在于事件表中。有些类可以作为多个事件存在。
首先我需要按价格降序排序,只使用 “阶级”表。
然后我只需要选择前4个最贵的课程 以前的结果。
然后我需要显示事件表中的所有信息 仅限前4名最贵的课程。这并不意味着只有4行,因为正如我所说,有些类有多个事件。
我设法让第一个TWO项目符号起作用,但是一旦我将前两个SELECT语句嵌入到最终的SELECT中,它就会显示所有类的事件,甚至是那些不在顶层的事件。 4。
SELECT x.*,
c.price,
c.class_name
FROM event x, class c
WHERE EXISTS (SELECT *
FROM (SELECT price, class_name
FROM class
ORDER BY price DESC)
WHERE ROWNUM <=4)
AND c.class_id=x.class_id;
所以在WHERE EXISTS之后的所有内容都可以工作,但它就像是忽略了WHERE EXISTS。
答案 0 :(得分:1)
那是因为 忽略了exists
。 Exists
返回true或false(或NULL)。您的子句通常返回四行。这些存在。所以,一切都归来了。也许你想要这个:
SELECT x.*, c.price, c.class_name
FROM event x JOIN
(SELECT *
FROM (SELECT class_id, price, class_name
FROM class
ORDER BY price DESC
) c
WHERE ROWNUM <= 4
) c
ON c.class_id = x.class_id;
答案 1 :(得分:1)
也许你的意思是:
SELECT x.*,
c.price,
c.class_name
FROM event x, class c
WHERE (c.price,c.class_name) IN (
SELECT price, class_name
FROM (SELECT price, class_name
FROM class
ORDER BY price DESC)
WHERE ROWNUM <=4)
AND c.class_id=x.class_id;
答案 2 :(得分:0)
您应首先选择按价格排序的前4个类,然后在外部SQL中获取事件数据
select evt.*, top_classes.price, top_classes.class_name
from event evt,
(select class_id, price, class_name
from (select price, class_id, class_name
from class
order by price DESC)
where rownum <=4) top_classes
where evt.class_id = top_classes.class_id;
答案 3 :(得分:0)
您错过了WHERE EXISTS
子查询中的联接。也许把它放在一个WITH
条款会有帮助吗?
WITH c1 AS ( -- Top 4 prices?
SELECT * FROM (
SELECT price, class_id
FROM class
ORDER BY price DESC
) WHERE rownum <= 4
)
SELECT x.*, c.price, c.class_name
FROM event x, class c
WHERE x.class_id = c.class_id
AND EXISTS ( SELECT 1 FROM c1 WHERE c1.class_id = c.class_id )
但我认为这样做更容易:
WITH c1 AS (
SELECT * FROM (
SELECT class_id, class_name, price
FROM class
ORDER BY price DESC
) WHERE rownum <= 4
)
SELECT x.*, c1.price, c1.class_name
FROM event x, c1
WHERE x.class_id = c1.class_id
希望这有帮助。