sql-cross表,一对多并找到最新的

时间:2018-03-13 23:45:41

标签: mysql sql one-to-many

所以我有两个数据库表:account, account_sub

一个account(具有唯一ID字段account_id)可能有account_sub

account_sub包含以下字段:status (an int, can be 1-6), start_date, duration, account_id(foreign key to account)

例如:

accounts
account_id      name
1               Apple
2               Orange
3               Banana
4               grape

account_subs 
id  account_id    status  date_start  duration
1    1            1       1/2/09            5
2    2            5       1/2/09           10
3    1            3       1/3/09           11
4    2            6       1/3/09           13
5    1            3       1/4/09           22
6    2            6       1/4/09           19
7    3            2       1/4/09          100
8    4            6       1/4/09           40

我想找到account_sub的最新last_update_date列表(由account决定)所有account_sub没有status = 1-4的{​​{1}}

这就是假设的结果:

account_subs:
account_id     account_sub_id
2                6
4                8

因为只有帐户2和4没有任何状态为1-4的account_sub,而帐户子6的开始日期+持续时间是最大的,最新的,account_sub 8也是帐户4的最新帐号。 /强>

因此,accountaccount_sub status != 1-4之间的account_sub应该在结果中包含最新的select account_sub from account_sub, account where account_sub.account_id = account.account_id and account_sub.status != 1 and account_sub.status != 2 and account_sub.status != 3 and account_sub.status != 4

这就是我现在所拥有的:

where

我认为这是不正确的,它不能得到我想要的东西,我想我需要account_sub中更复杂的条款,我不知道如何计算最近的With a as ( SELECT name_id , take , id_user FROM ((Proizv INNER JOIN Izdan ON Proizv.id = Izdan.id_proizv) INNER JOIN Exzemp ON Izdan.id = Exzemp.id_izdan) INNER JOIN log ON Exzemp.id = log.id_exzemp WHERE take IN ( SELECT TOP 2 take FROM log AS s WHERE s.id_user = log.id_user ORDER BY take DESC ) ), b as ( SELECT COUNT(name_id) AS cname , name_id FROM ((Proizv INNER JOIN Izdan ON Proizv.id = Izdan.id_proizv) INNER JOIN Exzemp ON Izdan.id = Exzemp.id_izdan) INNER JOIN log ON Exzemp.id = log.id_exzemp GROUP BY name_id ) select a.*, b.cname from a inner join b on a.name_id = b.name_id

1 个答案:

答案 0 :(得分:1)

select  account_id, id
from
(select account_sub.*, ( select count(*) from account_sub sub
                        where  date_add(sub.date_start, interval sub.duration day)  >= 
                               date_add(account_sub.date_start, interval account_sub.duration day)
                        and   sub.account_id = account_sub.account_id) as seq
from
account 
inner join
account_sub
on account.account_id = account_sub.account_id
where
account.account_id not in (select distinct accsub.account_id
                           from account_sub accsub
                           where
                           accsub.status in (1, 2, 3, 4))) t
where seq = 1 order by account_id;

sqlfiddle