mySQL添加搜索功能的功能

时间:2011-12-06 13:55:58

标签: php mysql search

这个mySQL查询在wordpress数据库中搜索项目,寻找标题中的相似之处。

SELECT ID, post_name, post_title, post_date 
FROM wp_posts 

WHERE wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish' AND wp_posts.post_title LIKE '%$my_text%' ORDER BY wp_posts.post_date DESC

我已将其扩展为包含标签。

SELECT ID, post_name, post_title, post_date 
FROM wp_posts 
LEFT JOIN wp_term_relationships 
ON        object_id = wp_posts.id
LEFT JOIN wp_terms 
ON        term_id = wp_term_relationships.term_taxonomy_id

WHERE wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish' AND wp_posts.post_title LIKE '%$my_text%'

OR wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish' AND wp_terms.name LIKE '%$my_text%'

这也有效,但它会在查询中添加帖子的提取次数。例如,如果我们键入仅出现在标题中的搜索词,但是相同的帖子ID在四个不相关标签的标签表中,则它从标题相似性中提取四次而不是一次。显然这个查询需要一些调整,但我对mySQL很新,需要一手。

2 个答案:

答案 0 :(得分:0)

以下是UNION选择的有用链接:http://www.mysqltutorial.org/sql-union-mysql.aspx

答案 1 :(得分:0)

...  WHERE 
wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish' 
AND (wp_posts.post_title LIKE '%$my_text%' OR wp_terms.name LIKE '%$my_text%')