![](/img/trans.png)
[英]MySQL select rows from a table where column is linked to another column in same table
[英]mysql select count rows from a table where column like values from another table
我將嘗試用一個例子來更好地解釋標題
表1示例
Id text
1 lorem ipsum doe
2 foo bar lorem ipsum jhon
3 bla bla ipsum tommy
表2示例
Id fullname name surname keyword
1 jhon doe jhon doe jhon
2 tom asd tom asd tom
3 sam frf sam frr sam
使用like或regexp的預期表結果?
fullname count(*)
jhon doe 2
tom asd 1
sam frf 0
非常感謝!
最簡單的是使用REGEXP。
SELECT fullname,
Count(t1.id)
FROM table1 t1
RIGHT JOIN table2 t2
ON t1.text REGEXP t2.keyword
GROUP BY fullname
我使用了一個正確的連接,這樣你就可以得到零的山姆(否則就會被淘汰)
用我的真實數據進行一些性能測試
t1 => 100,000行並且正在增長
t2 => 207行
測試1
SELECT
t2.fullname,
count(t1.id) AS total
FROM
table_1 AS t1
RIGHT JOIN
table_2 AS t2 ON t1.text REGEXP t2.keyword
GROUP BY t2.fullname
ORDER BY total DESC
212 seconds
測試2
SELECT
t2.fullname,
count(t1.id) AS total
FROM
table_1 AS t1
RIGHT JOIN
table_2 AS t2 ON t1.text LIKE CONCAT('%', t2.keyword, '%')
GROUP BY t2.fullname
ORDER BY total DESC
30 seconds
測試3
SELECT
t2.fullname,
count(t1.id) AS total
FROM
table_1 AS t1
RIGHT JOIN
table_2 AS t2 ON t1.text LIKE lower(CONCAT('%', t2.name, '%')) AND t1.text LIKE lower(CONCAT('%', t2.surname, '%'))
GROUP BY t2.fullname
ORDER BY total DESC
32 seconds
測試4
SELECT
t2.fullname,
count(t1.id) AS total
FROM
table_1 AS t1
RIGHT JOIN
table_2 AS t2 ON t1.text LIKE lower(CONCAT('%', t2.name, '%')) OR t1.text LIKE lower(CONCAT('%', t2.surname, '%'))
GROUP BY t2.fullname
ORDER BY total DESC
40 seconds
測試5
SELECT
t2.fullname,
count(t1.id) as total
FROM
table_1 as t1
RIGHT JOIN
table_2 as t2 ON t1.text LIKE CONCAT('%', t2.keyword, '%') OR (t1.text LIKE lower(CONCAT('%', t2.name, '%')) AND t1.text LIKE lower(CONCAT('%', t2.surname, '%')))
GROUP BY t2.fullname
ORDER BY total DESC
41 seconds
我會選擇測試5.最佳折衷結果/性能
還有什么建議嗎?
再次感謝你的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.