简体   繁体   中英

Combining if statements and multiple sql queries into one query

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;
}
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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM