SQL在友誼表中插入值基於 (SQL insert value in friendship table based on)


問題描述

SQL在友誼表中插入值基於 (SQL insert value in friendship table based on)

I’m taking a database course and I’ve got stuck on one of the questions. “For all cases where A is friends with B, and B is friends with C, add a new friendship for the pair A and C”.  This is as far as I’ve got

INSERT INTO 
    friend
SELECT DISTINCT 
    f1.ID1, f2.ID1 
FROM 
    friend f1 
    JOIN friend f2 using (ID2), 
    friend 
WHERE 
    f1.ID1 <> f2.ID1 
AND friend.ID1 <> f1.ID1 
AND friend.ID2 <> f1.ID2

The schema is here http://www.sqlfiddle.com/#!5/cf8b5/23

I wonder if somebody could give me a few hints on how to proceed. Thanks.

‑‑‑‑‑

參考解法

方法 1:

I think you have the basic concepts.

I'd do it like the following:

INSERT INTO friend
(ID1, ID2)
SELECT DISTINCT f1.ID1, f2.ID2
FROM friend f1
  INNER JOIN f2
    ON f1.ID2 = f2.ID1
      AND f1.ID1 <> f2.ID1
      AND f1.ID2 <> f2.ID2
WHERE f1.ID1 <> f2.ID2

方法 2:

I think it may be:

INSERT INTO friend
(ID1, ID2)
SELECT DISTINCT h.ID, f2.ID2
FROM Highschooler h 
inner join friend f1 on(h.ID=f1.ID1) 
inner join friend f2 on(f1.ID2=f2.ID1)
where h.ID <> f2.ID2
and not exists(select *
               from friend f3
               where f3.ID1=h.ID
               and f3.ID2 = f2.ID2)

方法 3:

First of all, I don't see the point of having both FRIEND and LIKES tables.

If friendship is represented by two highschoolers liking each other than one table with two ID columns is sufficient.

方法 4:

insert into friend
select f1.id1, f2.id2
from friend f1 join friend f2 on f1.id2 = f2.id1
where f1.id1 <> f2.id2
except
select * from friend

(by NinaCMarlin PiercesepLupussB‑Y)

參考文件

  1. SQL insert value in friendship table based on (CC BY‑SA 3.0/4.0)

#SQL






相關問題

如何組合表和視圖? (How do combine tables and views?)

Sql中的WHERE,結合兩個快速條件會成倍增加成本 (WHERE in Sql, combining two fast conditions multiplies costs many times)

Oracle : Выкарыстанне ўкладзенага запыту супраць выкарыстання адлюстравання (Oracle : Using nested query vs using mapping)

SQL在友誼表中插入值基於 (SQL insert value in friendship table based on)

SQL 查詢沒有返回任何值 (SQL query did not return any values)

PL/SQL 塊和循環練習 (PL/SQL block and LOOP exercise)

查找與日曆相比缺失的日期 (Find missing date as compare to calendar)

在 C# 中使用數據庫需要一些幫助 (Need some help working with databases in C#)

如何設計n多對多關係以使sql查詢更容易 (How to design n many to many relationship in order make sql query easily)

在 SQL 中從 3 個視圖創建一個視圖 (Creating a view from 3 views in SQL)

java while (resultset.next()) 不返回同一列中的所有數據 (java while (resultset.next()) does not return all data in the same column)

從訪問表單的文本字段傳遞開始和結束日期參數 (Pass start and end date parameter from text field of access form)







留言討論