Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 博士后:在一张桌子上加入两次_Sql_Postgresql - Fatal编程技术网

Sql 博士后:在一张桌子上加入两次

Sql 博士后:在一张桌子上加入两次,sql,postgresql,Sql,Postgresql,我(SQL noob)在Postgresql中有三个表,如下所示: 组 id | name | cat_id ----+--------+-------- 1 | group1 | 1 3 | group3 | 1 2 | group2 | 2 4 | group4 | 2 类别 id | name ----+------ 1 | cat1 2 | cat2 翻译 id | source | value | t

我(SQL noob)在Postgresql中有三个表,如下所示:

id |  name  | cat_id 
----+--------+--------
  1 | group1 |      1
  3 | group3 |      1
  2 | group2 |      2
  4 | group4 |      2
类别

id | name 
----+------
  1 | cat1
  2 | cat2
翻译

 id | source |  value  |   type   | res_id 
----+--------+---------+----------+--------
  1 | group1 | Gruppe1 | groups   |      1
  2 | group2 | Gruppe2 | groups   |      2
  3 | group3 | Gruppe3 | groups   |      3
  4 | group4 | Gruppe4 | groups   |      4
  5 | cat1   | Kat1    | category |      1
  6 | cat2   | Kat2    | category |      2
翻译表是应用程序的全局表,并使用“res_id”和“type”字段引用其他表。所以要得到“group1”的翻译,我需要使用“where res_id=1,type='groups”

我需要按以下格式列出这些组:

类别|组|翻译类别|翻译组

这个问题让我几乎达到了目的:

select category.name, groups.name, translation.value from groups                                                                                                              
join category on groups.cat_id = category.id
join translation on groups.id = translation.res_id
where type = 'groups';

当然,我没有找到翻译的类别,也不知道如何获得它。

我想你想要的是:

select
  category.name, 
  groups.name, 
  tg.value AS translated_group,
  tc.value AS translated_category
from groups                           
inner join translation tg on (groups.id = tg.res_id AND tg.type = "groups")
inner join category on groups.cat_id = category.id
inner join translation tc on (category.id = tc.res_id AND tc.type = "category");
i、 e.加入
translation
两次,为每个副本添加别名,并使用一个加入条件,该条件也会过滤
类型
字段

未测试,因为问题中没有
CREATE TABLE
INSERT
-表单示例数据

这些都不是特定于PostgreSQL的,都是标准SQL


顺便说一句,如果表名不混合使用复数和单数形式就更好了。

仅供参考,如果您也以表单形式提供示例数据,或者用psql输出代替,这将非常方便。对于这样一个简单的输出,这并不是真的必要,只是为了将来的参考。感谢您的提示,我不知道SQLFIDLE。很酷。很棒,非常有用。(如果没有最后一行,我假设是复制和粘贴的剩余内容)。我正试图了解最后一个连接-我是否应该将其视为已连接到组的category临时实例的连接?@FrankBrenner修复了最后一行。不,同一个表的第二个连接没有什么特别之处。要理解,请尝试
创建表myvalues(id integer,value integer);插入到myvalues中,从generate_series(1,3)x中选择x,x*2
。然后
从myvalues中选择a.*,b.*交叉连接myvalues b
。这是自连接的叉积。然后
内部连接的谓词过滤它,例如
从myvalues中选择a.*,b.*内部连接myvalues b ON(a.id=b.id)
。与上述唯一不同的是,有其他表连接在一起,而不是自连接。尝试使用玩具表。@FrankBrenner需要了解的一个关键问题是,当您连接到一个表时,您可以给它添加别名。此时,对该表的所有引用都必须使用别名。如果您多次连接一个表,但使用不同的别名,就好像你有两份有这些名字的表格。