计算列不包含下划线的值

时间:2014-01-06 17:23:53

标签: mysql sql escaping sql-like

我有以下查询,我想修改它,所以在我的计数中,而不是movies,它是没有下划线的值。对于第二个计数,我想要包含下划线的值。

以下是原始查询:

select document
, (count(distinct (case when table_name = 'movies' then keyword else null end)) * 100)
    + (count(distinct (case when table_name = 'movie_summaries' then keyword else null end)) * 50)
    as weight
from indexes where keyword in('the', 'hobbit')
group by document
order by weight desc limit 20

前3个权重如下:

  • 300
  • 250
  • 200

我修改了它,所以它看起来像这样,它似乎不起作用:

select document
, (count(distinct (case when table_name not like '%_%' then keyword else null end)) * 100)
    + (count(distinct (case when table_name like '%_%' then keyword else null end)) * 50)
    as weight
from indexes where keyword in('the', 'hobbit')
group by document
order by weight desc limit 20

现在前3个权重是:

  • 100
  • 100
  • 100

导致此变化的原因是什么?

CREATE TABLE `indexes` (
    `keyword` CHAR(15) NOT NULL,
    `document` INT(10) NOT NULL,
    `position` INT(11) NOT NULL,
    `table_name` CHAR(15) NOT NULL,
    PRIMARY KEY (`keyword`, `document`, `position`, `table_name`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;

1 个答案:

答案 0 :(得分:2)

核心问题是下划线是sql中的一个小丑角色。你应该像\_一样逃避它。

更多详情:Why does "_" (underscore) match "-" (hyphen)?