samedi 12 janvier 2019

MYSQL INNER JOIN - how to add extra IF statement?

I just learned how to use JOINS (so please be gentle ;) ), and made such querry:

SELECT 1
FROM `T1` INNER JOIN `T2`
ON `T1`.`T1_ID` = `T2`.`REQUIREMENT`
WHERE `T2`.`T1_ID`=XXX
AND `T1`.`STATEMENT`=YYY
AND `T2`.`REQUIREMENT`!=0 //last row does not work as intended!

It works perfect without last row: If T1_ID from T1 does match REQUIREMENT from T2 for given T1_ID (XXX) - it does work. I wanted additional STATEMENT from T1 to be match (YYY) - and it still does work.

But than I realized, that I need to exclude one cause: when T2.REQUIREMENT is equal to 0, I want this query to return 1 regardless of the JOIN formula. The problem is, that if T2.REQUIREMENT=0 I know for sure, that there will not be any T1.T1_ID entry that will match the JOIN requirements. So I understand, that this last row have no right to work like I'd wish it was.

What I need is some kind of IF statement. Something that would work like:

SELECT 1 
IF (`T2`.`REQUIREMENT`!=0) //if true, don't even go to join, and return 1
OR (my previous join query)

The thing is, that I have no idea how to implement such IF statement into mysql. Any ideas? Thanks.

Aucun commentaire:

Enregistrer un commentaire