ID name------------- 1 "one" 2 "two" 3 "three"
和一个带有第一个外键的table2:
ID tbl1_fk option value------------------------------- 1 1 1 1 2 2 1 1 3 1 2 1 4 3 2 1
现在我想作为查询结果:
table1.ID | table1.name | option | value------------------------------------- 1 "one" 1 1 2 "two" 1 1 3 "three" 1 "one" 2 1 2 "two" 3 "three" 2 1
我如何实现这一目标?
我已经尝试过:
SELECT table1.ID,table1.name,table2.option,table2.valueFROM table1 AS table1left outer JOIN table2 AS table2 ON table1.ID = table2.tbl1fk
但结果似乎省略了空值:
1 "one" 1 12 "two" 1 11 "one" 2 13 "three" 2 1
解决:感谢Mahmoud Gamal :(加上GROUP BY)
解决了这个问题
SELECT t1.ID,t1.name,t2.option,t2.valueFROM( SELECT t1.ID,t2.option FROM table1 AS t1 CROSS JOIN table2 AS t2) AS t1left JOIN table2 AS t2 ON t1.ID = t2.tbl1fk AND t1.option = t2.optiongroup by t1.ID,t2.valueORDER BY t1.ID,t1.name解决方法 您必须使用CROSS JOIN从第一个表中获取每个可能的名称组合以及第二个表中的选项.然后left JOIN这些组合与第二个表.就像是:
SELECT t1.ID,t2.option FROM table1 AS t1 CROSS JOIN table2 AS t2) AS t1left JOIN table2 AS t2 ON t1.ID = t2.tbl1_fk AND t1.option = t2.option
SQL Fiddle Demo
总结以上是内存溢出为你收集整理的PostgreSQL LEFT OUTER JOIN查询语法全部内容,希望文章能够帮你解决PostgreSQL LEFT OUTER JOIN查询语法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)