我对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 字段相同。
我该怎么做?
答案 0 :(得分:0)
不要加入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;