我有一个问题:
SELECT 1 FROM block_list WHERE client=123
嵌套在
中SELECT * FROM products
WHERE (client=123 AND product=234)
AND 1 <> (SELECT 1 FROM block_list WHERE client=123)
如果我将<>
替换为=
,它的工作原理(反之亦然)。但是如果用户在阻止列表中,我希望它返回NO记录。阻止是暂时的,仅影响网站的某些部分。
是否可以检查嵌套查询是否在WHERE子句中返回无结果?
答案 0 :(得分:2)
试试这个:
SELECT
*
FROM
products
WHERE
client = 123 AND
product = 234 AND (
SELECT 1
FROM block_list
WHERE client = 123
LIMIT 1
) IS NULL
答案 1 :(得分:2)
SELECT *
FROM products
WHERE
client=123
AND product=234
AND NOT EXISTS (SELECT 1 FROM block_list WHERE client=123)
答案 2 :(得分:1)
这似乎是一个很好的连接应用程序:
SELECT DISTINCT p.* FROM products p
JOIN block_list b USING (client)
WHERE b.client=123 AND p.product=234
答案 3 :(得分:0)
为了便于阅读/维护,我建议在选择产品之前将block_list
查询拆分为自己的单独查询。没有理由让像这样的单个查询的逻辑过于复杂。
如果客户端在阻止列表中,则原始查询设计不会返回任何结果。为什么甚至执行查询?
$rs = $dbh->query('SELECT * FROM block_list WHERE client = 123');
if($rs->rowcount() == 0 ) {
$rs = $dbh->query('SELECT * FROM products WHERE client = 123 AND product = 234');
// more code!
}