2015-11-07 22 views
1

我必須寫一個MySQL查詢與我必須通過文本消息,以檢查是否在所述消息中的任何單詞表中的檢查是否存在於表中的消息中的話

Table 
id  words 
1  arse 
2  ball 
3  sex 

是現有的「Cricket是一個蝙蝠和球類運動,每場比賽有11名隊員參加,場地中央有一個22碼長的長方形球場,在很多國家有1.2億球員參加,世界第二大最受歡迎的運動[1] [2] [3]每支球隊輪到球隊,試圖進球,而其他球隊出場。每回合被稱爲局「

是否可以在「like」opt中傳遞整個字符串?表中有大約1000個字將被阻止和檢查。 我想檢查給定的字符串是否包含此表中的任何單詞 如果是,那麼我需要匹配此表數據的單詞的計數。

檢查過很多post.but他們建議在下方選擇 如

select * from table where column like '%Cricket%' or column like '%is%' 
... 

緩慢且不可行 還有沒有其他的選擇嗎?

回答

0

你可以使用JOIN ON LIKE

CREATE TABLE posts(id INT, post VARCHAR(1000)); 

INSERT INTO posts 
SELECT 1, 'Cricket is a bat and ball game played between two teams of 11 players each on a field at the centre of which is a rectangular 22-yard-long pitch. The game is played by 120 million players in many countries, making it the world''s second most popular sport.[1][2][3] Each team takes its turn to bat, attempting to score runs, while the other team fields. Each turn is known as an innings '; 

CREATE TABLE words(id INT, word VARCHAR(100)); 

INSERT INTO words 
SELECT 1 , 'arse' UNION ALL SELECT 2,'ball' UNION ALL SELECT 3, 'sex'; 

查詢:

SELECT w.word, COUNT(*) AS `occ` 
FROM posts p 
JOIN words w 
ON p.post LIKE CONCAT('%', w.word, '%') 
WHERE p.id = 1 
GROUP BY w.word 
ORDER BY occ DESC; 

SqlFiddleDemo

輸出:

╔═══════╦═════╗ 
║ word ║ occ ║ 
╠═══════╬═════╣ 
║ ball ║ 1 ║ 
╚═══════╩═════╝