[英]trim() function : How to avoid empty string return if the argument is unset/null variable?
[英]How to unset or make condition true, If passed variable is empty or null
我有一个疑问...
SELECT * FROM table_name WHERE id = '$id'
如果$id
为empty
或null
,那么我需要从id
not null
表中获取所有数据
我已经尝试过如下,
SELECT
*
FROM
table_name
WHERE
(
('$id' != '' AND id = '$id')
OR
('$id' = '' AND id IS NOT NULL)
)
但是在没有if
条件的情况下寻找更好的解决方案,因为我有很多and
条件
提前致谢...
尝试这个:
SELECT *
FROM table_name
WHERE (id = '$id' OR $id IS NULL OR TRIM($id) = '')
如果$id
不为 null 且不为空,则将根据id
字段对其进行检查。 如果$id
为 null 或为空,则忽略过滤器并返回所有行。
更新
SELECT *
FROM table_name
WHERE (
(NULLIF(TRIM($id),'') IS NULL AND id IS NOT NULL) OR
id = $id
)
您可以使用php
本身进行技巧,例如:
$sql = 'SELECT * FROM table_name where id is not null';
if($id){
$sql .= ' and id = '.$id;
}
非常感谢@Akina 的评论...
这是解决方案...
SELECT * FROM table_name WHERE id = COALESCE(NULLIF($id, ''), id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.