最近碰到一个多条件查询的需求,但是如果某一个条件为空的话,那么为空的条件就不作为条件,如果全部为空,那么就应该全部都不作为条件,也就是查询所有数据,那么应该怎么实现呢?
CREATE DEFINER=`root`@`%` PROCEDURE `pr_backstate_query_sys_stock_all`(
in $stock_type tinyint,
in $game_type smallint,
in $room_id int,
in $cur_page int,
in $page_size int
)
RT:BEGIN
declare _cur_page int default 0;
declare _totals int default 0;
set _cur_page = ($cur_page-1) * $page_size;
select count(*) into _totals from room_stock_value_tbl
where game_id > 0 and
(game_id = $game_type or $game_type = '' or $game_type is null) and
(room_id = $room_id or $room_id = '' or $room_id is null) and
(stock_type = $stock_type or $stock_type = '' or $stock_type is null);
select *, _totals as totals
from room_stock_value_tbl
where game_id > 0 and
(game_id = $game_type or $game_type = '' or $game_type is null) and
(room_id = $room_id or $room_id = '' or $room_id is null) and
(stock_type = $stock_type or $stock_type = '' or $stock_type is null)
order by change_time desc
limit _cur_page, $page_size;
END
看存储过程可以知道,如果入参是空,那么加上一个入参为空的判断,那么就可以达到目的。如:
(room_id = $room_id or $room_id = ‘’ or $room_id is null)
当 $room_id 不为空,那么 $room_id作为条件,如果 $room_id为空,那么就让
$room_id is null 成立,就可以达到将 $room_id 不作为条件的目的。
mysql 分页功能比较简单,只需要传入当前页,和每页需要展示的条数即可,然后根据mysql的 limit 功能即可实现分页
这篇博客探讨了一个在MySQL中实现多条件查询的问题,当某些条件为空时,不应将其作为查询条件。通过在SQL语句中加入对空值的判断,可以达到条件为空时不影响查询的效果。同时,文章也提到了简单的MySQL分页功能,只需传入当前页数和每页显示数量,利用`LIMIT`关键字即可轻松实现分页操作。
4万+

被折叠的 条评论
为什么被折叠?



