SQLite表引用自身

时间:2013-01-05 13:20:24

标签: mysql sql sqlite subquery

我在SQLite中有一个表(联系人)和一个表(连接),它们非常自我解释:

contacts表包含id,firstname,secondname等信息。 连接表在一列中保存联系人的id,在另一列中保存联系人的id。

contacts

id | firstname | secondname
1  | test      | test
2  | asdf      | asdf
3  | qwer      | qwer

connection

id | contact_id | connection_to_id
1  | 1          | 2
2  | 1          | 3

如何进行查询以获取一个联系人所连接的姓名? 我尝试了这个,但它只给了我一个名字,即使有更多的连接:

SELECT
    c.firstname, c.secondname
FROM contacts c
WHERE
    c.id =
    (SELECT
        scon.connection_to_id
    FROM connection scon
    WHERE
        scon.contact_id = 1)

我只得到:

adsf asdf

但我想:

adsf asdf
qwer qwer

我希望你能理解我的问题并帮助我:)

2 个答案:

答案 0 :(得分:2)

最简单的只需稍加改动,c.id =需要更改为c.id IN

SELECT
    c.firstname, c.secondname
FROM contacts c
WHERE
    c.id IN
    (SELECT
        scon.connection_to_id
    FROM connection scon
    WHERE
        scon.contact_id = 1) ;

您还可以使用EXISTS相关子查询进行编写:

SELECT
    c.firstname, c.secondname
FROM contacts c
WHERE
    EXISTS
    (SELECT 1
    FROM connection scon
    WHERE
        scon.contact_id = 1
      AND 
        scon.connection_to_id = c.id) ;

JOIN(只要connection表中没有重复的行):

SELECT
    c.firstname, c.secondname
FROM contacts c
  JOIN connection scon
    ON scon.connection_to_id = c.id
WHERE
    scon.contact_id = 1 ;

答案 1 :(得分:1)

使用WHERE c.id IN (SELECT ...),即 IN 而不是=。