簡體   English   中英

Postgres:在桌子上加入兩次

[英]Postgres: Joining twice on a table

我(承認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");

即連接translation兩次,別名每個副本,並使用也過濾type字段的連接條件。

未經測試,因為問題中沒有CREATE TABLEINSERT -form示例數據。

這些都不是PostgreSQL特有的,它只是標准的SQL。

順便說一下,如果你不為表名混合使用復數形式和單數形式,那就更好了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM