我有一个我无法创建的复杂查询。我想用JOIN做,但不知道从哪里开始。我会尽可能清楚地解释我的问题。
我正在创建处理补偿的软件。每个补偿都可以有多个链接(如链中)。每个链接基本上都是一个客户。所以,我只会告诉你表结构:
客户
CustomerID | Name
补偿
CompensationID | CustomerID | Date
链接
LinkID | CompensationID | CustomerID | Sequential
现在,Sequential字段随着每个链接的增加而增加。让我通过填充表格来证明:
CustomerID | Name
-----------+-----
0 | Foo
1 | Bar
2 | Baz
CompensationID | CustomerID | Date
---------------+------------+------
0 | 0 | 2-2-2010
1 | 1 | 2-3-2010
LinkID | CompensationID | CustomerID | Sequential
-------+----------------+------------+-----------
0 0 0 0
1 0 2 1
2 0 1 2
因此无论LinkID / CompensationID / CustomerID是什么,Sequential总是在Links表中从0变为N(取决于补偿的链接数量)。
现在问题是:我想列出其Link符合以下要求的所有薪酬:
在链接中搜索 CustomerID = A. 顺序= 0(第一个链接)AND顺序=最后(在这种情况下为2) 列出补偿
这是我到目前为止所得到的:
SELECT * FROM Compensation JOIN Link ON Compensation.ID = Link.CompensationID
WHERE Link.CustomerID=A AND Link.Sequential = 0 AND Link.Sequential=LAST
这或多或少是伪SQL,因为我知道Link.Sequential不能同时为0和另一个值,但我不知道如何做到这一点。
任何帮助都将不胜感激。
谢谢。
P.S。 对不起文字的大墙。
答案 0 :(得分:1)
如果where语句中的子查询符合我的记忆:
select *
from
Compensation
left join
Link
on Compensation.CompensationID = Link.CompensationID
where
Link.CustomerID = :A
AND (
Link.Sequential = 0
OR
Link.Sequential = (
select MAX(Sequential) from Link where Link.CustomerID = :A
)
)
答案 1 :(得分:0)
尝试
SELECT c.*
FROM Compensation c
JOIN (select CompensationID, MAX(Sequential) AS LastSeq FROM Link GROUP BY CompensationID) AS LastOnes ON c.ID = LastOnes.CompensationID
JOIN (select CompensationID FROM Link WHERE CustomerID=A AND Sequential=0) AS FirststOnes ON c.ID = FirststOnes.CompensationID
JOIN Link AS l on l.CompensationID=c.CompensationID AND l.CustomerID=A AND l.Sequential=LastOnes.LastSeq