I am not so into DB (I am using MySql ) and I have the following problem trying to add an *IF** condition into this query:
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
As you can see what I am tryin to do is have a different part of my WHERE condition that depends by the value of the LCZ2.country_id retrieved in this subquery:
SELECT LCZ2.country_id FROM Localization AS LCZ2 WHERE LCZ2.id = 5
What is wrong in my query? What am I missing? How can I fix it?
Here is an immediate fix to your WHERE
clause:
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)
)
There is probably a better way of writing this, maybe without the subquery. If you can update your answer to better describe the problem, perhaps this answer can be simplified.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.