在sqlite3中构造复杂sql查询的最佳方法是什么

时间:2013-11-19 09:16:03

标签: sql database sqlite

我有两张桌子

用户

+----+-------+--------------+-------------------------------+
| ID | Login |   Password   |             Guid              |
+----+-------+--------------+-------------------------------+
|  1 | john  | johnpassword | 8f6nf7-r73hd3-43nhd7-df74hd   |
|  2 | mary  | marypassword | 4552mf-234jdf-43njduy-fwujd   |
|  3 | mark  | markpassword | dfh32-fdwe34-3442dr-43wdj45   |
|  4 | tom   | tompassword  | edri84-234jd-234jf-2345jd83   |
+----+-------+--------------+-------------------------------+

联系人

+----+---------------+------------------+---------+
| ID | RequestSender | RequestRecipient | Status  |
+----+---------------+------------------+---------+
|  1 |             1 |                2 |       3 |
|  2 |             1 |                3 |       3 |
|  3 |             4 |                1 |       3 |
+----+---------------+------------------+---------+

RequestSender和RequestRecipient是Users表中“ID”的外键。状态可以是1(请求),2(拒绝)和3(已接受)

我想通过提供他的 guid 来编写一个查询以从联系人表中获取所有john的联系人,并获得这样的结果

结果

+----+-------+-----------------------------+
| ID | Login |            Guid             |
+----+-------+-----------------------------+
|  2 | mary  | 4552mf-234jdf-43njduy-fwujd |
|  3 | mark  | dfh32-fdwe34-3442dr-43wdj45 |
|  4 | tom   | edri84-234jd-234jf-2345jd83 |
+----+-------+-----------------------------+

请注意,只要状态为3是有效的联系人关系,john的ID就可以在RequestSender或RequestRecipient上

我正在使用SQLITE3,因此我无法在SQL SERVER上使用某些复杂的东西

1 个答案:

答案 0 :(得分:1)

根本不是复杂的东西。这是非常基本的SQL:

SELECT ID, Login, Guid FROM Users WHERE ID IN (
    SELECT RequestSender FROM Contacts WHERE RequestRecipient=(
        SELECT ID FROM Users WHERE Guid=?1
    ) UNION SELECT RequestRecipient FROM Contacts WHERE RequestSender=(
        SELECT ID FROM Users WHERE Guid=?1
    )
)

只需将?1替换为所需的GUID。

编辑:更正了表名。