2016-02-08 58 views
1

我一直在提高我的SQL知識,但仍未能理解如何創建一些查詢。從數據庫中選擇相關記錄

我有一個SQL Server數據庫中的以下表:

用戶(ID,姓名)

貸款(id_sender,id_receiver,金額,日期,date_payment)

什麼將是一個有效的查詢:

  1. 選擇已發送貸款的用戶的名稱s到另一個用戶無論是在2014年和2015年
  2. 選擇誰已將貸款彼此

任何建議都非常感謝用戶的對(ID1,ID2)!


編輯1:

我嘗試:

1.

SELECT name FROM User WHERE id IN (
    SELECT id_sender FROM Loan WHERE 
    id_receiver IN (SELECT DISTINCT id_receiver WHERE YEAR(date) = 2014) AND 
    id_receiver IN (SELECT DISTINCT id_receiver WHERE YEAR(date) = 2015) 
) 

2.

SELECT id1, id2 FROM (
    SELECT DISTINCT id_sender as id1 FROM Loan 
    WHERE id_receiver IN (
     SELECT DISTINCT id_sender FROM Loan 
     WHERE id_receiver = ??? 
    ) 
    (?) 
) 
+0

那你嘗試至今。添加您的疑問。我們會嘗試修復它 –

+0

已添加它們。謝謝你的幫助! – shardl

回答

1

實施例1:如果你的date列具有索引,最好不要你選擇一個圍繞列的函數,以便實際使用索引。

SELECT name 
FROM User 
WHERE id IN (SELECT id_sender FROM Loan WHERE date >= '1/1/2014' AND date < '1/1/2015') 
    AND id IN (SELECT id_sender FROM Loan WHERE date >= '1/1/2015' AND date < '1/1/2016') 

示例2:您可以使用自連接來僅使用貸款表來查找匹配項。

SELECT 
    L1.id_sender AS id1, 
    L1.id_receiver AS id2 
FROM Loan L1 
    INNER JOIN Loan L2 
     ON L1.id_sender = L2.id_receiver 
      AND L2.id_sender = L1.id_receiver 
0
SELECT name 
FROM user 
WHERE id EXISTS (
    Select Distinct id_sender 
    FROM loan 
    WHERE year(date) between 2014 and 2015 
) 
SELECT s.id1,s.id2, s.monto, p.nombre 
FROM sap s INNER JOIN sop p 
ON s.id1 = p.id_comun INNER JOIN sap a 
ON a.id2 = p.id_comun 
UNION 
SELECT s.id1,s.id2, s.monto, p.nombre 
FROM sap s INNER JOIN sop p 
ON s.id1 = p.id_comun INNER JOIN sap a 
ON a.id2 = p.id_comun 
相關問題