【问题标题】:Convert SQLite join with multiple tables to PostgreSQL将具有多个表的 SQLite 连接转换为 PostgreSQL
【发布时间】:2017-08-17 09:34:25
【问题描述】:

我有这本字典和带有翻译的表格。我可以在 SQLite 中使用它来做一个不错的选择

SELECT e.slug,
       en.title,
       en.locale
FROM entities AS e
LEFT JOIN (
    locales AS en,
    entity_locales AS el 
) ON (
    el.entity_id = e.id
    AND el.locale_id = en.id
    AND en.locale == 'en'
)

产生:

present,  translation, en
missing,  NULL,        NULL

但我无法将其转换为 Postgres,因为我不明白当您在 SQLite 的 LEFT JOIN 中指定多个表时会发生什么:

SELECT e.slug,
       en.title,
       en.locale
FROM entities e
LEFT JOIN entity_locales el ON (el.entity_id = e.id)
JOIN locales en ON ( 
  el.locale_id = en.id
  AND en.locale = 'en'
)

只生产

present,  translation, en

有没有办法让它工作?

SQLite 格式的数据库结构:

CREATE TABLE IF NOT EXISTS "entities" (
  "id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
  "slug" varchar
);

CREATE TABLE IF NOT EXISTS "entity_locales" (
  "entity_id" integer,
  "locale_id" integer
);

CREATE TABLE IF NOT EXISTS "locales" (
  "id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
  "title" varchar,
  "locale" varchar
);

insert into entities(id, slug) values(1, 'present');
insert into entities(id, slug) values(2, 'missing');
insert into locales(id, title, locale) values(1, 'translation', 'en');
insert into entity_locales(entity_id, locale_id) values(1, 1);

【问题讨论】:

    标签: sql postgresql sqlite join


    【解决方案1】:

    您只对第二个表使用左连接,然后对第三个表使用内连接。您需要对第二个和第三个表之间的内连接的乘积使用左连接。

    试试这个:

    SELECT e.slug,
           en.title,
           en.locale
    FROM entities e
    LEFT JOIN 
    (
        entity_locales el 
        JOIN locales en ON ( 
          el.locale_id = en.id
          AND en.locale = 'en'
    )
    ) ON (el.entity_id = e.id)
    

    顺便说一句,您的初始脚本混合了隐式和显式连接。我建议不要使用隐式连接,因为显式连接是 SQL 的标准部分已有 25 多年了。

    【讨论】:

    • 如果同时使用多个语言环境,我可以只加入一次entity_locales,而不是重复el1el2 吗?
    • 加入一次,条件由en.locale = 'en'改为en.locale IN('en', 'fr', 'il')
    • 对不起,我的意思是这样的gist.github.com/firedev/d4d0179a378416ab5725a8d6cdfcdf3f
    猜你喜欢
    • 2014-07-02
    • 1970-01-01
    • 2021-04-02
    • 2012-08-24
    • 2016-05-12
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2015-04-03
    相关资源
    最近更新 更多