使用CTE查询使用Postgresql

时间:2018-09-19 18:39:07

标签: sql postgresql common-table-expression

我正在学习如何使用SQL CTE,并且我想比较两个查询以得到相同的答案(使用postgresql),但是我失败了,有人可以帮忙吗?

我创建此查询,并获得每个电影标题的总数(Sakila数据库):

SELECT COUNT(r.rental_id) rental_count, 
    f.title as "Film"
FROM film f 
JOIN inventory i 
ON f.film_id = i.film_id
JOIN rental r USING (inventory_id) 
GROUP BY f.title
ORDER BY rental_count DESC;

我想使用WITH(CTE)做同样的事情,为此,我创建了这段代码:

WITH table1 AS (           
            SELECT f.film_id,
            f.title as "Film"
            FROM film f),

 table2 AS (           
        SELECT r.inventory_id,
        COUNT(r.rental_id) rental_count,
        i.film_id,
        i.inventory_id
        FROM inventory i
        JOIN rental r USING (inventory_id)
        GROUP BY r.inventory_id, i.film_id, i.inventory_id)

SELECT *
FROM table1
JOIN table2 
ON table1.film_id = table2.film_id;

问题在于结果没有显示每个电影标题的总数,而是每个电影标题的单独显示。

2 个答案:

答案 0 :(得分:0)

要获得相同的结果,您必须像在第一个查询中一样对第二个查询进行汇总和分组:

WITH table1 AS (...),
     table2 AS (...)
SELECT count(table2.rental_count) AS rental_count,
       table1."Film"
FROM table1
   JOIN table2 USING (film_id)
GROUP BY table1."Film"
ORDER BY rental_count DESC;

基本上,您使用CTE而不是原始表。

答案 1 :(得分:0)

第二个CTE需要按胶片分组,以产生等效的最终结果。

Internal

只是一个音符;我不建议在单个查询中同时使用自然连接类型和非自然连接类型,这会造成混乱。

WITH table1 AS (
    SELECT
        f.film_id
      , f.title AS "Film"
    FROM film f
    )
, table2 AS (
    SELECT
        COUNT(r.rental_id) rental_count
      , i.film_id
    FROM inventory i
    JOIN rental r ON i.inventory_id = r.inventory
    GROUP BY i.film_id
    )
SELECT
      table2.rental_count
    , table1.Film
FROM table1
JOIN table2 ON table1.film_id = table2.film_id
ORDER BY rental_count DESC;