SQL select rows where field contains word from another table's fields

孤街浪徒 提交于 2019-12-13 19:49:55

问题


Using MySQL, I have a table with a name field. I want to check that name field against a set of "keywords" that indicate that the name is not a person, but a business.

In words: Get the entire row if the name contains any of the keywords.

My attempt: SELECT * FROM leads WHERE CONTAINS(leads.name, (SELECT word FROM keywords)); (Returns "Subquery returns more than 1 row")


回答1:


It does not work like that. You can use a join instead

SELECT l.* 
FROM leads l
JOIN keywords k on instr(leads.name, word) > 0 



回答2:


Something like this should do it:

SELECT distinct
    l.* 
FROM 
    leads l
    join keywords k on l.name = k.word

EDIT: or something like this if you have a comma delimited list

SELECT distinct
    l.* 
FROM 
    leads l
    join keywords k1 on l.name like concat('%,', k1.word)
    join keywords k2 on l.name like concat('%,', k2.word, ',%')
    join keywords k3 on l.name like concat(k2.word, ',%')
    join keywords k4 on l.name = k4.word



回答3:


Here you are:

SELECT * FROM leads WHERE leads.name IN (SELECT word FROM keywords);

Hope this helps.




回答4:


with numeric values, i use CONCAT with comma separator to be sure to find the exact value. In your case, it would be :

SELECT l.* FROM leads l 
JOIN keywords k 
on instr(CONCAT(',', leads.name, ','),  CONCAT(',', word, ',')) > 0


来源:https://stackoverflow.com/questions/31251314/sql-select-rows-where-field-contains-word-from-another-tables-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!