【问题标题】:How to get fields from a table where its primary key is used in another table in 2 possible fields如何从一个表中获取字段,该表的主键在另一个表中的 2 个可能字段中使用
【发布时间】:2016-07-22 16:33:48
【问题描述】:

我有 2 个 sql 表

    CREATE TABLE users(userID INTEGER PRIMARY KEY AUTOINCREMENT, alias TEXT NOT NULL)
    CREATE TABLE friends(userID1 INTEGER, userID2 INTEGER, PRIMARY KEY(userID1, userID2))

当 2 个用户想成为朋友时,我通过在 friends 表中插入一行来创建一个新的关系 btw 2。该行中 2 个朋友的 userID 的顺序无关紧要,但无论顺序如何,它都应该是唯一的。

问题 1: 我的第二张桌子目前没有反映我想要的。我的意思是我可以做到这一点,虽然我不希望这样,但这很好:

    INSERT INTO friends VALUES(1,2);
    INSERT INTO friends VALUES(2,1);

是否可以在我的 sql 表中强制执行此约束,或者如果还没有反向顺序的关系,我应该使用查询进行检查。

问题 2: 例如,如果我有 userID,获取朋友列表(userIDalias)的最佳 sql 查询是什么? :

    INSERT INTO users VALUES(1, 'A');
    INSERT INTO users VALUES(2, 'B');
    INSERT INTO users VALUES(3, 'C');
    INSERT INTO users VALUES(4, 'D');
    INSERT INTO friends VALUES(1, 2);
    INSERT INTO friends VALUES(2, 3);
    INSERT INTO friends VALUES(4, 1);
    INSERT INTO friends VALUES(2, 4);

我想要:

For userID=1: (2, B) and (4, D)
For userID=2: (1, A), (3, C) and (4, D)
For userID=3: (2, B)
For userID=4: (1, A) and (2, B)

额外问题:我可以改进表格以更好地反映我想要的吗?

非常感谢!

【问题讨论】:

  • 很好的问题,框架很好

标签: sql database sqlite


【解决方案1】:

一次一个问题。从此结构更改插入:

insert into table
(field1, field2, etc)
values
(value1, value2, etc)

到这个结构

insert into table
(field1, field2, etc)
select distinct value1, value2, etc
from someSmallTable
where not exists
(subquery to check for existing rows)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多