我有三个表,下面有相关的详细信息
1. Primary words
+----+---------+
| id | word |
+----+---------+
| 1 | Machine |
+----+---------+
| 2 | phone |
+----+---------+
2. Alternative words
+----+------------+-----------+
| id | primary_id | word |
+----+------------+-----------+
| 1 | 1 | system |
+----+------------+-----------+
| 2 | 1 | feature |
+----+------------+-----------+
| 3 | 2 | telephone |
+----+------------+-----------+
3. product table
+----+------------------+
| id | name |
+----+------------------+
| 1 | mobile system |
+----+------------------+
| 2 | computer machine |
+----+------------------+
| 3 | wired telephone |
+----+------------------+
现在扭曲的是,每当用户在产品表中使用“机器”搜索,然后显示带有表名的产品的结果具有“机器”或“系统”或“功能”,如果用“系统”或“功能”搜索,那么显示“机器”或“系统”或“功能”的结果。或者副主管。
请您建议我如何解决这个问题?
答案 0 :(得分:1)
如果我理解你的要求......
<强> SQL 强>
SELECT *
FROM Product P
WHERE EXISTS(SELECT fw.Word --(6) select all products that exist in this query
FROM (SELECT pw.Word --(1) select all Primary words matching input
FROM PrimaryWords pw
WHERE pw.Word = 'machine'
UNION --(3) union the results from both selects
SELECT aw.Word --(2) select all Alternative words that match input or have its primary matching it
FROM PrimaryWords pw INNER JOIN AlternativeWords aw
ON pw.Id = aw.PrimaryId
WHERE pw.Word = 'machine'
OR aw.Word = 'machine') as fw --(4) alias the result
WHERE p.Name LIKE '%' || fw.Word || '%'); -- (5) filter products that match the valid words
您可以阅读()中编号所排序的评论。
答案 1 :(得分:1)
首先,您需要将这两个表格数据加载一个,然后给出条件。
Select word from(
SELECT id,word FROM PrimaryWords
Union all
Select primaryid,word from AlternativeWords a
) where id in ( select id from primarywords where word='yoursearchketword'
Union
Select primaryid from AlternativeWords where word='yoursearchketword')
根据您的产品表更新了答案。
现在您需要交叉加入产品表,因为它们之间没有任何关系。
还有一件事是你必须在这里使用like运算符来比较你想要的结果和prouct表的名称列。在这里,我给出了一个小小的想法如何实现这一点,但你可以很容易地改进它。
Select a.word,b.name from
(Select word from(
SELECT id,word FROM PrimaryWords
Union all
Select primaryid,word from AlternativeWords a
) where id in ( select id from primarywords where word='yoursearchketword'
Union
Select primaryid from AlternativeWords where word='yoursearchketword')) a, product b
Where a.word LIKE CONCAT('%',name, '%');
答案 2 :(得分:-1)
我建议把它放在这样一个表中:
id | primary_id | word
1 | 1 | machine
2 | 2 | phone
3 | 1 | system
4 | 1 | feature
5 | 2 | telephone
查询将如下所示,我们以machine
字为例:
Select word from MyTable where primary_id in
(select primary_id from MyTable where word = "machine")
输出:machine
,system
,feature
<强>更新强>
如果您有更多列,例如显示这些单词的相关程度,您可以再添加一个表来映射单词,如下所示:
id | w1_id | w2_id | relation
1 | 1 | 3 | 80
2 | 2 | 5 | 90
3 | 1 | 4 | 60
4 | 3 | 4 | 60
单词表格仅列出如下字样:
id| word
1 | machine
2 | phone
3 | system
4 | feature
5 | telephone
在this thread中,您会找到一个长篇讨论,讨论如何设计架构布局以及如何检索数据的提示。