PostgreSQL在查询

时间:2016-07-08 09:08:52

标签: sql postgresql

我有2个实体;我的erd中的castfilm和staff有一个共同的属性employeeid。现在,我想在postgre中查询以显示与具有employeeid no的特定人员相关的属性。 307他的fname和lname分别是David和Kaye。

我的观点如下:enter image description here

我想要展示的属性是fname,lname,castrole,filmtitle,filmgenre,filmyear,companyname,staffposition,artistname和soundtitle,这些属性与名为David Kaye的员工的电影有关

这是我的疑问:

SELECT distinct fname,lname,castrole, filmtitle, filmgenre, filmyear, companyname
FROM employee,
     castfilm,
     film,
     production,
     company
 WHERE employee.employeeid = 307
   AND employee.employeeid = castfilm.employeeid 
   AND castfilm.filmid = film.filmid 
   AND production.companyid = company.companyid 
   AND production.filmid = film.filmid

[输出] [2]

如何展示与David Kaye所在的特定电影相关的其他工作人员和演员?

1 个答案:

答案 0 :(得分:0)

您可以使用EXISTS声明:

  

EXISTS的参数是一个任意的SELECT语句或子查询。   对子查询进行求值以确定它是否返回任何行。如果   它返回至少一行,EXISTS的结果为" true&#34 ;;如果   子查询不返回任何行,EXISTS的结果为" false"。

在子查询中,您应该检查给定的filmid employeeid中是否存在castfilm。这个employeeid应该是307。

像这样:

SELECT distinct fname,lname,castrole, filmtitle, filmgenre, filmyear, companyname
FROM employee,
     castfilm,
     film,
     production,
     company
 WHERE employee.employeeid = castfilm.employeeid 
   AND castfilm.filmid = film.filmid 
   AND production.companyid = company.companyid 
   AND production.filmid = film.filmid
   AND EXISTS (
    SELECT
        employeeid
    FROM
        castfilm
    WHERE
        filmid = film.filmid AND
        employeeid = 307
    );

请注意,子查询中使用了film.filmid

此外,正如@jarlh所说,您可以使用JOIN语法,如下所示:

SELECT
    fname,
    lname,
    castrole,
    filmtitle,
    filmgenre,
    filmyear,
    companyname
FROM
    employee
    JOIN castfilm
    ON (employee.employeeid = castfilm.employeeid)
    JOIN film
    ON (castfilm.filmid = film.filmid)
    JOIN production
    ON (film.filmid = production.filmid)
    JOIN company
    ON (production.companyid = company.companyid)
WHERE
    EXISTS (
        SELECT
            employeeid
        FROM
            castfilm
        WHERE
            filmid = film.filmid AND
            employeeid = 307
    );