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

标签 mysql sql database join rdbms

我不太喜欢 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_id 应与第二个查询中返回的 LCZ2.country_id AS country_id 字段相同。

我该怎么做?

最佳答案

不要加入本地化表,而是加入您想要的子查询。这里没有太多魔法。只需将子查询括在括号中,为其指定一个别名(我在下面使用了 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;

关于mysql - 如何将查询的输出(就好像它是一个表)连接到 SQL 查询中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48261739/

相关文章:

mysql - MySQL索引使用

如果用 group by 子句找不到记录,MySQL 返回 0 作为值

asp.net - 网络负载平衡场景中的 session 状态

mysql - 在 Sql 中对数据进行分组

php - Facebook 成员(member)资格(错误 : MySql)

java - 通过脚本文件或通过 Java 代码初始化 SQL 数据库是否有任何继承优势?

MySQL/ASP - 令人困惑的 SQL 查询

MySQL/Percona 5.6 : INSERT INTO a table after a table is ALTERed

mysql - SQL - 从一行中获取特定值然后使用该值

php - Mysql:检查范围时间冲突