如何在 MySQL 中多次使用空变量?
我正在尝试检查 MySQL 语句中是否有 2 个空变量,但我似乎可以得到非常正确的语法。这是我现在所拥有的,它一直给我一个错误。谁能告诉我如何正确地做到这一点?
SELECT threads, userid, username, usergroupid
FROM " . TABLE_PREFIX . "user
WHERE
" . iif(!empty($exuserids), "AND userid NOT IN ($exuserids)") . "
" . iif(!empty($exgroups), "AND usergroupid NOT IN ($exgroups)") . "
ORDER BY threads DESC
LIMIT 1
I am trying to check for 2 empty variables in a MySQL statement but I can seem to get the syntax quite right for it. Here is what I have now and it keeps giving me an error. Can anyone please tell me how I can do this properly?
SELECT threads, userid, username, usergroupid
FROM " . TABLE_PREFIX . "user
WHERE
" . iif(!empty($exuserids), "AND userid NOT IN ($exuserids)") . "
" . iif(!empty($exgroups), "AND usergroupid NOT IN ($exgroups)") . "
ORDER BY threads DESC
LIMIT 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用:
在指定“AND ...”之前需要有一个 WHERE 子句 -
1 = 1
将被优化掉。这是动态 SQL 中使用的一个技巧,可以使 WHERE 子句连接更容易。Use:
There needs to be a WHERE clause before you specify "AND ..." - the
1 = 1
will be optimized out. It's a trick used for dynamic SQL to make WHERE clause concatenation easier.好吧,难怪它会给你一个错误。您是否使用 PHPkit 或其他为您提供
iif
的东西,因为尽管您没有这么说,但上面的内容是用 PHP 编写的,而iif
不是该语言的一部分。现在,即使您拥有它,为什么不漂亮地编译该语句 - 将条件收集在数组中,使用 AND 进行内爆,如果不为空则添加一个 WHERE 条件。
最后,在查询中使用变量是 SQL 注入攻击的一个秘诀。
Well no wonder it gives you an error. Are you using PHPkit or something else that gives you
iif
Because, despite you do not say so, the above is written in PHP andiif
is not part of the language.Now, even if you have it why not compile the statement prettily -- gather the conditions in an array, implode with AND and add a WHERE condition if it's not empty.
Finally, having variables in queries is a recipe for SQL injection attacks.