创建可能为空关系的PostgreSQL查询
假设我有下面的表,其中每个表中的id是主键,第二个表中的actor是第一个表的外键创建可能为空关系的PostgreSQL查询,sql,postgresql,null,relationship,Sql,Postgresql,Null,Relationship,假设我有下面的表,其中每个表中的id是主键,第二个表中的actor是第一个表的外键 table: actors id | name ----+-------------------------------- 1 | Paul Rudd 2 | Danny Devito 3 | Mark Ruffalo 4 | David Allen Grier table:
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.
这对我来说很好,看看吧。您在查询中没有使用正确的单引号
”
SELECT
coalesce(m.name, 'none'), a.name
FROM actors a
JOIN movies m
ON m.id = a.id;
Postgresql:
SELECT m.name, a.name
FROM movies m
RIGHT OUTER JOIN actors a
ON m.actors = a.id;
@steve你可以查看我提供的演示链接,它工作正常。我犯了一个错误;这不是mysql,而是postgresql。我更新了帖子,对不起。@steve更新了我的答案。您需要使用
coalesce()
。请看我提供的演示。谢谢,我最终解决了一个right outter加入。我已经用解决方案更新了帖子。@steve你应该非常清楚你需要什么。你的帖子与你刚刚更新的完全不同。不要在问题中加上“已解决”。添加答案并接受该答案。否则,您的问题将保持“未解决”