首页 > 解决方案 > 创建一个可能存在 Null 关系的 PostgreSQL 查询

问题描述

假设我有以下表格,其中每个中的 id 是主键,第二个中的 actor 是第一个的外键。

 table: actors
 id |              name              
----+--------------------------------
  1 | Paul Rudd            
  2 | Danny Devito             
  3 | Mark Ruffalo 
  4 | David Allen Grier      

table: movies
 id |     name      | actors
----+---------------+----------------
  1 | So this is 40 |              1
  2 | Avengers      |              3
  3 | Twins         |              2

我需要编写一个 sql 查询,它将选择所有电影名称以及他们的演员和没有电影的演员

这就是我所拥有的:

SELECT IFNULL(m.name, 'none'), a.name
FROM actors a
JOIN movies m
ON m.id = a.id;

我得到:

ERROR:  function ifnull(character varying, unknown) does not exist
LINE 1: SELECT IFNULL(n.name, 'none'), l.name

HINT:  No function matches the given name and argument types. You might need 
to add explicit type casts.

标签: sqlpostgresqlnullrelationship

解决方案


它对我来说工作正常,在这里查看。您没有'在查询中使用正确的单引号。

SELECT 
    coalesce(m.name, 'none'), a.name
FROM actors a
JOIN movies m
ON m.id = a.id;

推荐阅读