如何在与另一个表关联的单词表中搜索单词列表?

时间:2013-05-09 06:24:58

标签: mysql

以下是我设置的3个表格。 'words'和'word_part_mapping'表是通过索引零件表中零件名称中的所有单词自动生成的。

//'parts' table
+----------+--------------+
| part_num | part_name    |
+----------+--------------+
| 10111    | front bumper |
| 10112    | rear bumper  |
+----------+--------------+


//'words' table
+------+------------+
| id   | word       |
+------+------------+
| 1    | front      |
| 2    | bumper     |
| 3    | rear       |
+------+------------+



//'word_part_mapping' association table
+---------+----------+
| word_id | part_num |
+---------+----------+
| 1       | 10111    |
| 2       | 10111    |
| 3       | 10112    |
| 1       | 10112    |
+---------+----------+

如果用户搜索“前保险杠”并且我希望查询返回包含用户搜索的所有单词的结果,我该如何查询?

SELECT p.* 
FROM words w 
LEFT JOIN word_part_mapping wpm ON w.id=wpm.word_id
LEFT JOIN parts p ON wpm.part_num=p.part_num
WHERE w.word='front' AND w.word='bumper'

显然,上述查询不起作用,因为该单词不能同等于'front'和'bumper'。如果我做OR,这是有效的,但我不希望这样,因为它返回太多结果(数据库中有50,000多个部分)。

============================================== < / p>

编辑:最后工作......

SELECT p.* 
FROM words w 
LEFT JOIN word_part_mapping wpm ON w.id=wpm.word_id 
LEFT JOIN parts p ON wpm.part_num=p.part_num 
WHERE w.word IN('front','bumper') 
GROUP BY p.part_num 
HAVING COUNT(DISTINCT w.word) = 2

其中2是用户搜索的术语数

2 个答案:

答案 0 :(得分:0)

如何只看这个part_name

SELECT * 
  FROM parts
 WHERE part_name LIKE '%front%' 
   AND part_name LIKE '%bumper%'

<强> SQLFiddle

答案 1 :(得分:0)

终于有了工作......

SELECT p.* 
FROM words w 
LEFT JOIN word_part_mapping wpm ON w.id=wpm.word_id 
LEFT JOIN parts p ON wpm.part_num=p.part_num 
WHERE w.word IN('front','bumper') 
GROUP BY p.part_num 
HAVING COUNT(DISTINCT w.word) = 2

其中2是用户搜索的术语数