匹配列表中的多个列关键字

时间:2014-12-11 06:38:38

标签: python python-2.7 sqlite

内容表

content_id | content                               |
-----------x---------------------------------------x
    1      | he is python and javascript developer |

和关键字表

key_id | Keyword        | content_id |
-------x----------------x------------x
   1   | python         |     1      |
   2   | developer      |     1      |
   3   | javascript     |     1      |

在python sqlite中,需要一个查询才能知道几个关键字来自同一个内容

search_term = "python developer"
terms = search_term.split()          #['python','developer']

for term in terms:
    result = cursor.execute('''SELECT con.content_id FROM keywords AS key 
                               LEFT JOIN content as con
                               ON key.content_id = con.content_id 
                               WHERE key.keyword = ?''',(term))


Pseudocode : if i get content_id = 1,1 for more than two times returning  the content_id

问题:如果多个关键字与同一内容上的关键字表匹配,则返回content_id(s)

2 个答案:

答案 0 :(得分:0)

此查询计算有多少匹配关键字:

SELECT content_id,
       COUNT(*) AS kw_count
FROM keywords
WHERE Keyword IN ('python', 'developer')
GROUP BY content_id

要仅获取包含多个关键字的行,请在分组列中添加条件:

...
HAVING kw_count > 1

答案 1 :(得分:0)

我猜你试图让content_ids没有重复。试试这个:

SELECT con.content_id 来自内容AS con WHERE content_id in(     SELECT content_id     FROM关键字AS键     WHERE keyword =?)