我一直在提高我的SQL知识,但仍然无法理解如何创建一些查询。
我在SQL Server数据库中有以下表格:
用户(ID,姓名)
贷款(id_sender,id_receiver,金额,日期,日期_付款)
什么是有效查询:
非常感谢任何建议!
编辑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 :(得分: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
答案 1 :(得分:0)
1
SELECT name
FROM user
WHERE id EXISTS (
Select Distinct id_sender
FROM loan
WHERE year(date) between 2014 and 2015
)
2
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