sql - Postgres : Joining twice on a table

标签 sql postgresql

我(公认的 SQL 菜鸟)在 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 and 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 表单示例数据。

这些都不是 PostgreSQL 特有的,它只是标准 SQL。

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

关于sql - Postgres : Joining twice on a table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25290764/

相关文章:

mysql - SQL SELECT 或 CROSS JOIN 多个帐户和按行列中的 SUM 值

mysql - 如何使用两列得到第三列的结果

php - 当我向其中添加 LIMIT 关键字时,SQL 不工作

mysql - 变量在 IN 子句中不起作用

c# - 使用 Entity Framework 将集合另存为 JSON

postgresql - information_schema.tables 和 pg_tables 的区别

python - psycopg2 每次执行都会产生不同的表和游标不滚动到开头

postgresql - 当列的长度未知时如何添加前导零?

PostgreSQL pgAgent 的工作无法工作

MySQL,多行分隔字段