[英]How to get fields from a table where its primary key is used in another table in 2 possible fields
I have 2 sql tables 我有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))
When 2 users want to be friends, I create a new relationship btw the 2 by inserting a row in the friends table. 当2个用户希望成为朋友时,我通过在friends表中插入一行来创建2之间的新关系。 The order for the userID of the 2 friends in the row do not matter but it should be unique, whatever the order. 该行中2个朋友的userID的顺序无关紧要,但是无论顺序如何,它都应该是唯一的。
Question 1: My second table do not currently reflect what I want. 问题1:我的第二张桌子目前未反映我想要的内容。 I mean I can do this and it's fine while I don't want it to be: 我的意思是我可以做到,但我不希望这样做是很好的:
INSERT INTO friends VALUES(1,2);
INSERT INTO friends VALUES(2,1);
Is it possible to enforce this constraint in my sql table, or should I check with a query if there is not already a relationship in the reversed order. 是否可以在我的sql表中强制执行此约束,或者是否应该以查询方式检查查询是否还没有反向关系。
Question 2: What is the most optimal sql query to get the list of friends ( userID and alias ) if I have a userID , if I have for example: 问题2:如果我有一个userID ,那么例如,如果要获取朋友列表( userID和alias ),最最佳的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);
I want: 我想要:
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)
Bonus question: Can I improve the tables to better reflect what I want? 奖励问题:我可以改进表格以更好地反映我想要的吗?
Thanks a lot! 非常感谢!
One question at a time. 一次提出一个问题。 Change your insert from this structure: 从此结构更改插入:
insert into table
(field1, field2, etc)
values
(value1, value2, etc)
to this structure 这个结构
insert into table
(field1, field2, etc)
select distinct value1, value2, etc
from someSmallTable
where not exists
(subquery to check for existing rows)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.