0

我有一张将单词相互关联的表格。

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

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

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

banana

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

4

3 回答 3

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' ;
于 2012-06-04T17:31:35.867 回答
0

可以使用INTERSECTSQL 中的命令来查找多个查询的交集;即,返回他们所有人的共同点。

例如:

select field1 from table1 where id = 5
intersect
select field1 from table2 where id < 5
于 2012-06-04T17:12:23.683 回答
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"))

(未测试)

于 2012-06-04T17:38:43.257 回答