MySQL:带有通配符的空字符串不会返回任何结果

时间:2018-01-05 04:45:23

标签: mysql sql

我有一个程序,看起来如下。
仅当出于某种原因设置了 _keyword 时,它才会返回结果 但如果 _keyword 是一个空字符串,则不返回任何内容。

★_keyword是此过程的动态变量,而不是NULL

这种行为可能是什么原因?

set @cart_count := 0;
set @fav_count := 0;
set @access_count := 0;
set @i := 0;

set @orderCol := 'itemId';
set @offset := 1;
set @maxLimit := 30;
set @keyword := concat('%', _keyword, '%');
set @targetDate := '2018-01-05';

select
  t.item_id,
  t.item_title,
  t.item_url,
  t.item_status,
  t.cart_count,
  t.favourite_count,
  t.access_count,
  UNIX_TIMESTAMP(t.created_date) as created_date
from (
       select
         t1.item_id,
         t1.item_title,
         t1.item_url,
         t1.item_status,
         t1.created_date,
         @val1 := if(@item_id1=t1.item_id, t1.cart_count - @cart_count, t1.cart_count) as cart_count,
         @val1 := if(@item_id1=t1.item_id, t1.favourite_count - @fav_count, t1.favourite_count) as favourite_count,
         @val1 := if(@item_id1=t1.item_id, t1.access_count - @access_count, t1.access_count) as access_count,
         @cart_count := t1.cart_count,
         @fav_count := t1.favourite_count,
         @access_count := t1.access_count,
         @item_id1 := t1.item_id
       from some_table t1
       where date(t1.created_date) = @targetDate AND (t1.item_title like @keyword or t1.item_id like @keyword)
     ) t
where  (@i := @i+1) BETWEEN @offset and @maxLimit
       and t.cart_count > 0

1 个答案:

答案 0 :(得分:0)

我不知道您在何处/如何设置_keyword的值,但我建议您认为您拥有的空字符串值实际为NULL。请考虑以下两个查询:

select 'empty string matches' from dual where 'hello' like '%%';
select 'null matches' from dual where 'hello' like concat('%', NULL, '%');

Demo

输出中只会显示empty string matchesCONCAT('%', NULL, '%')与任何内容不匹配的原因是NULL表示未知。因此,我们不能一般地说它与任何东西相匹配或不匹配。