2008-12-23 37 views
0

我有两个表,作者和样式之间的关系。 每个作者都与一种风格相关联,特殊情况下作者没有风格(IS NULL)。选择一个可为空的参考

将引用设置为NULL没有问题,但执行查询以选择作者和样式时出现问题。

例如,查询:

SELECT "authors"."id", "authors"."name", "styles"."name", "authors"."comments" FROM 
"authors" , "styles" WHERE "authors"."style" = "styles"."id" 

只是忽略了有一个NULL风格的作家(如预期)。

我需要做一个选择,也列出作者与NULL风格,就像左连接会做(我不能使用左连接出于某些原因)。

有一个解决方案不包含显式连接?

回答

4

最明显的解决方案是LEFT OUTER JOIN。

请参见:http://www.postgresql.org/docs/8.1/static/tutorial-join.html

如果你不想使用显式联接,你应该能够使用UNION

SELECT "authors"."id", "authors"."name", "styles"."name", "authors"."comments" FROM 
"authors" , "styles" WHERE "authors"."style" = "styles"."id" 
UNION 
SELECT "authors"."id", "authors"."name", "", "authors"."comments" FROM 
"authors" WHERE "authors"."style" IS NULL 
0
SELECT "authors"."id", "authors"."name", "styles"."name", "authors"."comments" FROM "authors" , "styles" WHERE "authors"."style" = "styles"."id" OR "authors"."style" = null 

你试过了吗?

+0

是的,这会导致作者有一种关系会将所有样式 – Kknd 2008-12-23 12:42:27

0

从我的理解,你只需要扩大您的查询,包括NULL:

SELECT "authors"."id", "authors"."name", "styles"."name", "authors"."comments" 
FROM "authors" , "styles" 
WHERE "authors"."style" = "styles"."id" OR "authors"."style" IS NULL 
+0

不幸的是,它使作者用null样式与所有样式有关系 – Kknd 2008-12-23 12:43:06