我正在尝试加速PHP脚本,我目前在Mysql域中推送一些PHP逻辑。如果第一个Select没有返回任何行,或者计数为零,有没有办法制作不同的选择查询?
请记住,第一个查询需要先运行,第二个查询应该仅,如果第一个查询返回一个空集。
SELECT * FROM proxies WHERE (A='B') || SELECT * FROM proxies WHERE (A='C')
对于上面的2个查询,我有这个代码,但似乎每次运行两次查询(一次计数,一次返回)。有更好的方法吗?
IF (SELECT count(*) FROM proxies WHERE A='B')>0
THEN SELECT * FROM proxies WHERE A='B'
ELSEIF (SELECT count(*) FROM proxies WHERE A='C')>0
THEN SELECT * FROM proxies WHERE A='C'
END IF
答案 0 :(得分:14)
一种选择是将UNION ALL
与EXISTS
:
SELECT *
FROM proxies
WHERE A='B'
UNION ALL
SELECT *
FROM proxies
WHERE A='C' AND NOT EXISTS (
SELECT 1
FROM proxies
WHERE A='B'
)
这将返回proxies
表中的行A='B'
(如果存在)。但是,如果它们不存在,它将查找A='C'
的那些行。
答案 1 :(得分:7)
SELECT *
FROM proxies
WHERE A=(CASE WHEN
(SELECT COUNT(*) FROM proxies WHERE A='B') > 0 THEN'B'
ELSE 'C' END)
<强>更新强>
SELECT *
FROM proxies
WHERE (
CASE WHEN (SELECT COUNT(*) FROM proxies WHERE A='B' LIMIT 1) > 0 THEN
(A='B')
WHEN (SELECT COUNT(*) FROM proxies WHERE A='C' LIMIT 1) > 0 THEN
(A='C')
WHEN (SELECT COUNT(*) FROM proxies WHERE A='D' LIMIT 1) > 0 THEN
(A='D')
ELSE 1=2 END)
答案 2 :(得分:1)
在一般情况下,A
有多个值(例如,&#39; B&#39;,&#39; C&#39;,&#39; D&#39;,& #39; E&#39;等)并且您只想检索属于存在的最低值的行,然后您将使用以下查询。这也适用于您所暴露的特定情况。
SELECT p1.*
FROM proxies p1
LEFT JOIN proxies p2
ON p1.A > p2.A
WHERE p2.A IS NULL
答案 3 :(得分:0)
我认为这或多或少涵盖了您尝试做的事情。如果您需要返回的行数,只需从mysqli-&gt; num_rows
中获取值$db = new mySQLi(etc);
//run your first query
$query = "SELECT * FROM proxies WHERE A='B'";
$result = $db->query($query);
//check for rows returned
if($result->num_rows > 0){
//if there are rows get them
while($row = $result->fetch_assoc()){
//deal with the results
}
} else {
//otherwise run your other query and get those results
$query = "SELECT * FROM proxies WHERE A='C'";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
//deal with the results
}
}
答案 4 :(得分:0)
另一种方式:
SELECT A INTO @v FROM proxies ORDER BY A LIMIT 1;
SELECT * FROM proxies WHERE A=@v