Reputation: 1687
I have a server where it limits the amount of sql queries you can make per hour, so I'm trying to find a way to combine all 3 of my if statements and sql queries into one sql query, and am wondering if that's possible? Please take a look at my code:
$text1 = "one";
$text2 = "two";
$text3 = "three";
$data = SELECT text FROM tableName WHERE
text LIKE '%$text1%' AND
text LIKE '%$text2%' AND
text LIKE '%$text3%' order by rand() limit 1;
if ($data == null) {
$data = SELECT text FROM tableName WHERE
text LIKE '%$text1%' AND
text LIKE '%$text2%' order by rand() limit 1;
}
if ($data == null) {
$data = SELECT text FROM tableName WHERE
text LIKE '%$text1%' order by rand() limit 1;
}
Upvotes: 2
Views: 98
Reputation: 35337
SELECT text,
((text LIKE '%$text1%') + (text LIKE '%$text2%') + (text LIKE '%$text3%')) as `matches`
FROM tableName
HAVING `matches` > 0
ORDER BY `matches` DESC, rand() LIMIT 1
This should sort the values by the number of matches as each expression will be treated as integer 1 on a match or 0 otherwise.
Upvotes: 2