I have a very large MySQL statement looped through php foreach and each loop connected to the previous with union all. I will simplify the statement to the core of my problem, if needed I can of course also add more details later on request.
I have this table
+--------+-----------+-----------+
| ID | LANG | TITLE |
+--------+-----------+-----------+
| 1 | EN | T-A |
+--------+-----------+-----------+
| 1 | FR | T-A |
+--------+-----------+-----------+
| 2 | FR | T-B |
+--------+-----------+-----------+
| 3 | DE | T-C |
+--------+-----------+-----------+
| 3 | EN | T-C |
+--------+-----------+-----------+
I want to write a WHERE condition in the SQL SELECT that should show me for each ID maximum one result. But it should show results only if LANG is FR or EN. On top FR should be prefered and EN should only be displayed as alternative if no FR is available for the ID. So the result would look like this.
+--------+-----------+-----------+
| ID | LANG | TITLE |
+--------+-----------+-----------+
| 1 | FR | T-A |
+--------+-----------+-----------+
| 2 | FR | T-B |
+--------+-----------+-----------+
| 3 | EN | T-C |
+--------+-----------+-----------+
I have tried to build something by myself with IF - ELSE / CASE but I am not very experienced with SQL so any help would be much appreaciated.
A simplified SQL I tried would be something like
SELECT * FROM `table`
WHERE `table`.`ID` = 1
IF `table`.`LANG` = 'FR'
BEGIN
AND `table`.`LANG` = 'FR'
END
ELSE
BEGIN
AND `table`.`LANG` = 'EN'
END
union all
SELECT * FROM `table`
WHERE `table`.`ID` = 2
IF `table`.`LANG` = 'FR'
BEGIN
AND `table`.`LANG` = 'FR'
END
ELSE
BEGIN
AND `table`.`LANG` = 'EN'
END
union all
SELECT * FROM `table`
WHERE `table`.`ID` = 3
IF `table`.`LANG` = 'FR'
BEGIN
AND `table`.`LANG` = 'FR'
END
ELSE
BEGIN
AND `table`.`LANG` = 'EN'
END
Sitenote I may not use any construct with ORDER BY combined with LIMIT 1 since I am looping the SQL through a php for each loop multiple times.
EDIT: SOLUTION that worked for me
SELECT * FROM `table1`
WHERE ID = 1
AND lang = 'FR'
OR (lang = 'EN' AND ID NOT IN (SELECT ID FROM table1 WHERE lang = 'FR'))