如何将查询的输出(就好像它是一个表)连接到sql查询中?

iovurdzv  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(367)

我不太喜欢sql,我有以下问题。我正在使用mysql
我必须更改此查询:

SELECT 
        USR.id                              AS hq_user_id,
        USR.local_user_id,       
        LCZ.id                              AS localization_id,  
        LCZ.description                     AS description,
        LCZ_COUNTRY_LEVEL.id                                AS country_id,
        LCZ_COUNTRY_LEVEL.description                AS country_description
FROM Localization AS LCZ

INNER JOIN User AS USR
    ON USR.localization_id = LCZ.id

INNER JOIN Localization AS LCZ_COUNTRY_LEVEL
    ON LCZ_COUNTRY_LEVEL.country_id = LCZ.country_id

WHERE USR.local_user_id = 999

正在删除第二个内部联接:

INNER JOIN Localization AS LCZ_COUNTRY_LEVEL
    ON LCZ_COUNTRY_LEVEL.country_id = LCZ.country_id

并将其替换为我编写的另一个查询的输出:

SELECT
    LCZ2.id                 AS localization_id_nation_level,
    LCZ2.country_id         AS country_id
FROM Localization AS LCZ2
WHERE
     LCZ2.region_id is null
AND  LCZ2.province_id is null
AND  LCZ2.city_id is null
AND  LCZ2.district_id is null
AND  LCZ2.town_id is null
AND  LCZ2.village_id is null

联接条件应为:
lcz.country\u id应与第二个查询中返回的lcz2.country\u id字段相同。
我该怎么做?

2q5ifsrm

2q5ifsrm1#

而不是加入 Localization 表中,联接到所需的子查询。这里没什么魔力。只需将子查询用括号括起来,给它一个别名(我使用 t ,然后在连接条件中使用该别名。

SELECT 
    USR.id AS hq_user_id,
    USR.local_user_id,       
    LCZ.id AS localization_id,  
    LCZ.description,
    LCZ_COUNTRY_LEVEL.id AS country_id,
    LCZ_COUNTRY_LEVEL.description AS country_description
FROM Localization AS LCZ
INNER JOIN User AS USR
    ON USR.localization_id = LCZ.id
INNER JOIN
(
    SELECT country_id
    FROM Localization AS LCZ2
    WHERE
        region_id IS NULL AND
        province_id IS NULL AND
        city_id IS NULL AND
        district_id IS NULL AND
        town_id IS NULL AND
        village_id IS NULL
) t
    ON LCZ.country_id = t.country_id
WHERE USR.local_user_id = 999;

相关问题