在sql中创建2+视图

2ekbmq32  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(277)

我试图解决这个问题https://www.hackerrank.com/challenges/placements/problem 以下代码跳转出错

CREATE VIEW T AS (
SELECT STUDENTS.ID ,STUDENTS.NAME,PACKAGES.SALARY,FRIENDS.FRIEND_ID
FROM STUDENTS JOIN FRIENDS ON STUDENTS.ID=FRIENDS.ID
    JOIN PACKAGES ON STUDENTS.ID=PACKAGES.ID
);
CREATE VIEW T2 AS (
SELECT T.NAME
FROM  T JOIN PACKAGES ON T.FRIEND_ID=PACKAGES.ID
WHERE T.SALARY<PACKAGES.SALARY
ORDER BY PACKAGES.SALARY;
);
SELECT *
FROM T2;

但是这个

CREATE VIEW T AS (
SELECT STUDENTS.ID ,STUDENTS.NAME,PACKAGES.SALARY,FRIENDS.FRIEND_ID
FROM STUDENTS JOIN FRIENDS ON STUDENTS.ID=FRIENDS.ID
    JOIN PACKAGES ON STUDENTS.ID=PACKAGES.ID
);

SELECT T.NAME
FROM  T JOIN PACKAGES ON T.FRIEND_ID=PACKAGES.ID
WHERE T.SALARY<PACKAGES.SALARY
ORDER BY PACKAGES.SALARY;

作品。为什么?这是因为我创建了多个视图还是其他原因?

ocebsuys

ocebsuys1#

试着去掉括号:

CREATE VIEW T AS 
    SELECT S.ID, S.NAME, P.SALARY, F.FRIEND_ID
    FROM STUDENTS S JOIN
        FRIENDS F
        ON S.ID = F.ID JOIN
        PACKAGES P
        ON S.ID = P.ID;

CREATE VIEW T2 AS
    SELECT T.NAME
    FROM T JOIN 
         PACKAGES P
         ON T.FRIEND_ID = P.ID
    WHERE T.SALARY < P.SALARY
    ORDER BY P.SALARY;

您会注意到,我引入了表别名,因此查询更易于编写和读取。
括号不是 CREATE VIEW 语法,因此查询被解释为子查询。我想这就打乱了对 ORDER BY .

相关问题