I would like to turn this code into a more pure MySQL. This code fetches a row according to each word in $words and it creates $translated word array.
$words = array("word1","word2","word3"...);
$translated = array();
foreach($words as $word){
$query = "
select * from (
select text1,text2,text3
from table1
union
select text1,text2,text3
from table2
union
select text1,text2,text3
from table3
) as u
where u.text1 = ? or u.text2 = ?";
$prepare = $database -> prepare($query);
$prepare -> execute(array($word,$word));
$fetch = $prepare -> fetch();
if($fetch["text3"]){ $push = $fetch["text3"]; }
else if($fetch["text1"]){ $push = $fetch["text1"]; }
else{ $push = $word; }
array_push($translated, $push);
}
This PHP solution seems really inefficient to me. I would like to find a pure MySQL solution. So far I've been working on this MySQL but it lacks the ending logic.
$query="
select
if(text2='word1',text3,0) as W1,
+ if(text2='word2',text3,0) as W2,
+ if(text2='word3',text3,0) as W3,
...
from (
select text1,text2,text3
from table1
union
select text1,text2,text3
from table2
union
select text1,text2,text3
from table3
) as u where
u.text1 in('word1','word2','word3'...) or
u.text3 in('word1','word2','word3'...)
";
This give out something like:
Array (
[0] => Array ( [word1] => 0 [word2] => word22 [word3] => 0 [word4] => 0 )
[1] => Array ( [word1] => word23 [word2] => 0 [word3] => 0 [word4] => 0 )
[2] => Array ( [word1] => 0 [word2] => 0 [word3] => word24 [word4] => 0 ) )
I can column search for non-zero entry to find the translation. BUT, I am not sure how to add logic to the MySQL to select default text1 if text3 is missing.
if($fetch["text3"]){ $push = $fetch["text3"]; }
else if($fetch["text1"]){ $push = $fetch["text1"]; }
else{ $push = $word; }
array_push($translated, $push);