如何将使用if语句的查询修复为where条件?

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

我不太喜欢db(我使用的是mysql),我在尝试向这个查询中添加一个*if**条件时遇到了以下问题:

SELECT
    LCZ1.id                                          AS localization_id,
    LCZ1.description                                 AS localization_description, 
    CNT.id                                           AS country_id,
    CNT.country_name                                 AS country_name,
    CNT.isActive                                     AS country_is_active,
    RGN.id                                           AS region_id,
    RGN.region_name                                  AS region_name,
    PRV.id                                           AS province_id,
    PRV.province_name                                AS province_name,
    DST.id                                           AS district_id, 
    DST.district_name                                AS district_name,
    SCT.id                                           AS sector_id,
    SCT.sector_name                                  AS sector_name

FROM Localization                                   AS LCZ1
LEFT JOIN Country                                   AS CNT
     ON LCZ1.country_id = CNT.id
LEFT JOIN Region                                    AS RGN
     ON LCZ1.region_id = RGN.id
LEFT JOIN Province                                  AS PRV
     ON LCZ1.province_id = PRV.id 
LEFT JOIN District                                  AS DST
     ON LCZ1.district_id = DST.id
LEFT JOIN Sector                                    AS SCT
     ON LCZ1.sector_id = SCT.id

WHERE
     (LCZ1.country_id = (SELECT LCZ2.country_id FROM Localization AS LCZ2 WHERE LCZ2.id = 5))

IF(LCZ2.country_id = 1)
BEGIN
    AND
        LCZ1.region_id is not null
END

IF(LCZ2.country_id = 2)
BEGIN
    AND
        LCZ1.province_id is not null

END

如您所见,我正在尝试做的是使where条件的不同部分取决于在此子查询中检索到的lcz2.country\u id的值:

SELECT LCZ2.country_id FROM Localization AS LCZ2 WHERE LCZ2.id = 5

我的问题是什么?我错过了什么?我该怎么修?

aamkag61

aamkag611#

这是一个立即解决你的问题 WHERE 条款:

WHERE
    (LCZ1.country_id = (SELECT LCZ2.country_id FROM Localization AS LCZ2 WHERE LCZ2.id = 5)) AND
    (
        (LCZ1.country_id = 1 AND LCZ1.region_id IS NOT NULL) OR
        (LCZ1.country_id = 2 AND LCZ1.provice_id IS NOT NULL) OR
         LCZ1.country_id NOT IN (1, 2)
    )

也许有更好的方法来编写这个,也许没有子查询。如果你能更新你的答案来更好地描述问题,也许这个答案可以简化。

相关问题