如何将使用IF语句的查询固定为WHERE条件?

时间:2018-06-26 13:35:28

标签: mysql sql database rdbms

我不是很喜欢数据库(我正在使用 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_id 的值:

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

我的查询出了什么问题?我想念什么?我该如何解决?

1 个答案:

答案 0 :(得分:2)

这是您的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)
    )

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