“SQL社交网络修改练习”(斯坦福DB公开课)

时间:2013-02-11 03:49:01

标签: sql database sqlite

对于A是B的朋友,B是C的朋友的所有情况,为A和C对添加新的友谊。不要添加重复的友谊,已经存在的友谊或与自己的友谊。

我的尝试如下,导致语法错误:

insert into Friend 
  select F1.ID1, F2.ID2
  from Friend F1, Friend F2 
  where F1.ID2 = F2.ID1 and F1.ID1 <> F2.ID2 and (F1.ID1, F2.ID2) not in (
    select * from Friend
);

预期的查询结果应该是(无法从上述查询中生成):

1025    John    12  2
1101    Haley   10  3
1247    Alexis  11  7
1304    Jordan  12  8
1316    Austin  11  6
1381    Tiffany 9   6
1468    Kris    10  6
1501    Jessica 11  7
1510    Jordan  9   5
1641    Brittan 10  3
1661    Logan   12  4
1689    Gabriel 9   8
1709    Cassand 9   7
1782    Andrew  10  10
1911    Gabriel 11  5
1934    Kyle    12  7

数据库架构和数据是:

Highschooler
ID      name       grade
1510    Jordan     9
1689    Gabriel    9
1381    Tiffany    9
1709    Cassandra  9
1101    Haley      10
1782    Andrew     10
1468    Kris       10
1641    Brittany   10
1247    Alexis     11
1316    Austin     11
1911    Gabriel    11
1501    Jessica    11
1304    Jordan     12
1025    John       12
1934    Kyle       12
1661    Logan      12

Friend
ID1     ID2
1510    1381
1510    1689
1689    1709
1381    1247
1709    1247
1689    1782
1782    1468
1782    1316
1782    1304
1468    1101
1468    1641
1101    1641
1247    1911
1247    1501
1911    1501
1501    1934
1316    1934
1934    1304
1304    1661
1661    1025
1381    1510
1689    1510
1709    1689
1247    1381
1247    1709
1782    1689
1468    1782
1316    1782
1304    1782
1101    1468
1641    1468
1641    1101
1911    1247
1501    1247
1501    1911
1934    1501
1934    1316
1304    1934
1661    1304
1025    1661

Likes
ID1     ID2
1689    1709
1709    1689
1782    1709
1911    1247
1247    1468
1641    1468
1316    1304
1501    1934
1934    1501
1025    1101

1 个答案:

答案 0 :(得分:4)

你可以这样做,

insert into Friend
select distinct F1.ID1, F2.ID2
from Friend F1, Friend F2
where F1.ID2 = F2.ID1 and F1.ID1<>F2.ID2 
      and F1.ID1 not in (select F3.ID1 from Friend F3 where F3.ID2=F2.ID2);