2012-04-18 63 views
1

請考慮下表中的消息。其中一些標籤的格式爲{bar|***}***爲任何東西(字母,數字,標點符號)。搜索數據庫中具有多個{tokens}的字符串

id message 
--------------------------------------------------- 
1 foo {bar|112} baz {bar|foo} {bar|215.54} 
2 lorem ipsum {bar|foo} dolor {bar|samet} digitas 
3 last {bar|t} label example 
4 string with no label 
5 another {zoo} string with {foo|ads} label 

如果我想尋找的所有消息以形式{欄的至少一個標籤| *}我查詢:

SELECT * FROM messages WHERE message LIKE '%{bar|%'; 

但現在,我需要一個查詢與我只能選擇具有最多兩個這樣的標籤,這些消息:

id message 
--------------------------------------------------- 
2 lorem ipsum {bar|foo} dolor {bar|samet} digitas 
3 last {bar|t} label example 

換句話說:有沒有一種方法(在MySQL中)來計算消息中標籤的數量,並只返回其中包含一個或兩個標籤的消息?

+0

你可以用嵌套的indexof調用來做到這一點,並斷言第三個indested調用返回-1 – Bohemian 2012-04-18 19:02:03

回答

1
SELECT * FROM messages WHERE (LENGTH(message) - LENGTH(REPLACE(message,'{bar|','')))/5 BETWEEN 1 AND 2; 

這應該有效。