2010-06-21 48 views
15

我有這個標記表開關與LIKE SELECT查詢裏面的MySQL

CREATE TABLE IF NOT EXISTS `Tags` (
    `id_tag` int(10) unsigned NOT NULL auto_increment, 
    `tag` varchar(255) default NULL, 
    PRIMARY KEY (`id_tag`), 
    UNIQUE KEY `tag` (`tag`), 
    KEY `id_tag` (`id_tag`), 
    KEY `tag_2` (`tag`), 
    KEY `tag_3` (`tag`), 
    KEY `tag_4` (`tag`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2937 ; 

INSERT INTO `Tags` (`id_tag`, `tag`) VALUES 
    (1816, '(class'), 
    (2642, 'class\r\n\r\nâ?¬35'), 
    (1906, 'class\r\nif'), 
    (1398, 'class'), 
    (2436, 'class)'), 
    (1973, 'class:\n1.'), 
    (2791, 'classes'), 
    (1325, 'New'), 
    (2185, 'pack'), 
    (1905, 'packed'), 
    (1389, 'WebClass'); 

我想取其中標籤匹配關鍵字classpacknew,與指示另一場沿所有記錄,其中3個關鍵字實際上與標籤字段相匹配。

下面的查詢不給出正確的結果 查詢1

select id_tag, 
case tag 
    when tag LIKE "%class%" then "class" 
    when tag LIKE "%new%" then "new" 
    when tag LIKE "%pack%" then "pack" 
end as matching_tag 
from Tags 
where tag LIKE "%class%" OR tag LIKE "%new%" OR tag LIKE "%pack%" 

我必須使用類似的情況中。否則完成匹配工作。下面的查詢工作: -

查詢2

select id_tag, 
case tag 
    when "class" then "class" 
    when "new" then "new" 
    when "pack" then "pack" 
end as matching_tag 
from Tags 
where tag = "class" OR tag = "new" OR tag = "pack" 

有什麼不對查詢1.請幫助。

+0

+1 DDL和樣本數據 – Unreason 2010-06-21 07:56:52

+0

這裏有什麼問題嗎?查詢1給出了11個結果,並且有11個條目,這是預期的。查詢2中的where子句不同並更改結果集。 – Cez 2010-06-21 08:06:22

+0

btw,你可以使用'WHERE標記IN(「class」,「new」,「pack」)' – abatishchev 2010-06-21 08:11:02

回答

24

Mysql支持兩種情況的變體,您在查詢2中使用的變體較不靈活,但僅支持單個變量上的相等性。其他版本沒有指定任何變量情況後再條件不一定是唯一的平等:

select id_tag, 
case 
    when tag LIKE "%class%" then "class" 
    when tag LIKE "%new%" then "new" 
    when tag LIKE "%pack%" then "pack" 
end as matching_tag 
from Tags 
where tag LIKE "%class%" OR tag LIKE "%new%" OR tag LIKE "%pack%" 

進一步的細節

編輯見documentation: 這裏的,爲什麼您的查詢#1返回它詳細說明一下返回:

case tag 
    when tag LIKE "%class%" then "class" 
    when tag LIKE "%new%" then "new" 
    when tag LIKE "%pack%" then "pack" 
end as matching_tag 

期望得到一個文字值進行比較when ... then 之間在上述情況下的表達式tag LIKE "%class%"tag LIKE "%new%"tag LIKE "%pack%"都是在實際案例比較之前評估的。但是(!),會發生什麼,它們變成0或1,並且與標記的值相比,它是匹配任何字符的第一個0值(字符將被轉換爲0) - 這與您的第一個查詢的結果。

這裏有一個查詢,顯示了有關的用語的邏輯值:

select id_tag, tag LIKE "%class%", tag LIKE "%new%", tag = 0, case tag  when tag LIKE "%class%" then "class"  when tag LIKE "%new%" then "new" when tag LIKE "%pack%" then "pack" end as matching_tag from Tags where tag LIKE "%class%" OR tag LIKE "%new%" OR tag LIKE "%pack%"; 

這就是爲什麼你會得到意想不到的效果;無聲的CAST在這裏是一個標準的陷阱。

+0

非常感謝!得到了很快的答案 – 2010-06-21 09:21:32

+0

感謝您的擴展解釋 – Cez 2010-06-22 21:41:59

6

只想提醒,約else子句:

case 
    when tag LIKE "%class%" then "class" 
    when tag LIKE "%new%" then "new" 
    when tag LIKE "%pack%" then "pack" 
    else "no one" 
end as matching_tag