简体   繁体   English

将if语句和多个sql查询合并为一个查询

[英]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?我有一台服务器,它限制了你每小时可以进行的 sql 查询的数量,所以我试图找到一种方法将我的所有 3 个 if 语句和 sql 查询组合成一个 sql 查询,我想知道这是否可能? 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.这应该按匹配数对值进行排序,因为每个表达式在匹配时将被视为整数 1,否则将被视为 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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