如何从两个表中获取同义词?

时间:2014-12-01 07:43:47

标签: mysql database

我必须使用php / MySql从word和同义词表中获取数据:

  words              synonyms
 id|word          wordid|synonymid
 -------            -------
  1|A                  1|2    
  2|B                  2|1
  3|C                  2|3
                       3|2

所以我想搜索单词A并找回单词B.也许INNER-JOIN是一个解决方案? 我已经有了一个解决方案,但它需要两个查询。

2 个答案:

答案 0 :(得分:2)

您只需要两个带words表的JOIN。

SELECT w2.word
FROM words AS w1
JOIN synonyms AS s ON s.wordid = w1.id
JOIN words AS w2 ON s.synonymid = w2.id
WHERE w1.word = 'A'

答案 1 :(得分:0)

尝试使用此查询:

SELECT t1.id, t1.word, GROUP_CONCAT(t3.word) AS synonyms
FROM words t1 
JOIN synonyms t2 ON t1.id = t2.wordid
JOIN words t3 ON t2.synonymid = t3.id
WHERE t1.word='B';

此查询将以方便的格式返回答案:

+----+------+----------+
| id | word | synonyms |
+----+------+----------+
|  2 | B    | A,C      |
+----+------+----------+