SQL获取与所有键相关的所有结果

时间:2012-06-04 17:04:49

标签: mysql sql sql-match-all

我有一张相互关联的词汇表。

table_word_relationships
+-------------+-------------+
|   WORD_A    |  WORD_B     |
+-------------+-------------+
|   cat       |   dog       |
+-------------+-------------+
|   cat       |   rabbit    |
+-------------+-------------+
|   owl       |   cat       |
+-------------+-------------+
|   bird      |   dog       |
+-------------+-------------+
|   dog       |   banana    |
+-------------+-------------+
|   banana    |   cat       |
+-------------+-------------+

我需要对它运行两种类型的查询。一个很容易。给我所有与“狗”这个词有关的词语

"SELECT * FROM table_word_relationships WHERE WORD_A = 'dog' OR WORD_B = 'dog'";

结果将是:

cat
bird
banana

第二个是我遇到麻烦的...... 我需要查询与单词数组中所有单词有关系的所有单词...

所以,在英语中我会说“给我所有与”狗“这个词有关系的词,并且还与”CAT“这个词有关系 结果将是:

banana

因为香蕉是唯一与两个关键词相关的词。什么是适当类型的SQL语句?

3 个答案:

答案 0 :(得分:2)

查询1应为:

SELECT word_b AS word
FROM table_word_relationships 
WHERE word_a = 'dog' 

UNION DISTINCT

SELECT word_a 
FROM table_word_relationships 
WHERE word_b = 'dog' ;

查询2变得非常复杂,因为您只将每个连接存储在一行中。一种可能的方式:

SELECT
    dog.word
FROM
  ( SELECT word_b AS word
    FROM table_word_relationships 
    WHERE word_a = 'dog' 

    UNION DISTINCT

    SELECT word_a 
    FROM table_word_relationships 
    WHERE word_b = 'dog' 
  ) AS dog

  JOIN

  ( SELECT word_b AS word
    FROM table_word_relationships 
    WHERE word_a = 'cat' 

    UNION DISTINCT

    SELECT word_a 
    FROM table_word_relationships 
    WHERE word_b = 'cat' 
  ) AS cat

  ON cat.word = dog.word ;

如果要将所有连接存储在两行(cat, dog)(dog, cat)中,那么您的查询都会更简单。

然后查询1:

SELECT word_b AS word
FROM table_word_relationships 
WHERE word_a = 'dog' ;

查询2:

SELECT
    dog.word_b AS word
FROM 
    table_word_relationships AS dog
  JOIN 
    table_word_relationships AS cat
      ON cat.word_b = dog.word_b 
WHERE 
      dog.word_a = 'dog' 
  AND 
      cat.word_a = 'cat' ;

答案 1 :(得分:0)

您可以在SQL中使用INTERSECT命令查找多个查询的交集;即,返回所有人的共同点。

e.g:

select field1 from table1 where id = 5
intersect
select field1 from table2 where id < 5

答案 2 :(得分:0)

正如您在评论中所解释的那样,您有2张桌子。我假设第一个表名为words,有两列:idword。并且关系表包含对于单词表的id和id2外键。

然后你可以尝试这样的事情:

select distinct word from words w
where 
(exists 
(select * from table_word_relationships r 
inner join word w2 on w2.id = r.id2 
inner join word w3 on w3.id = r.id 
where (w.id = r.id1 and w2.word = "CAT") or (w.id = r.id2 and w3.word = "CAT"))
and
(exists 
(select * from table_word_relationships r 
inner join word w2 on w2.id = r.id2 
inner join word w3 on w3.id = r.id 
where (w.id = r.id1 and w2.word = "DOG") or (w.id = r.id2 and w3.word = "DOG"))

(未经测试)