我有3张桌子,一张带有价格,另一张带有客户,最后一张带有客户的家属,如健康保险。当我有1个客户和1个从属时,第一个从属的值是一个,当我有两个从属时,第二个从属的值是不同的,但第一个是相同的。
我需要一个查询,该查询显示相关项表并获取每个相关项的值,最大4个相关项。
从属表
val timeValues = videoFileMap.values.mapNotNull { it.firstOrNull() }
.map { it.time - System.currentTimeMillis() }
价格表
+--------------+--------+---------+------------+
| id_dependent | name | number | primary_id |
+--------------+--------+---------+------------+
| 51 | Carlos | 956585 | 2 |
| 52 | João | 985868 | 2 |
| 53 | Jaime | 985868 | 2 |
| 54 | Evan | 985847 | 3 |
| 55 | Kaus | 584788 | 3 |
+--------------+--------+---------+------------+
我需要什么
+----------+---------+-----------+-------+---------+
| price_id | Product | Dependent | Value | Plan_id |
+----------+---------+-----------+-------+---------+
| 11 | Plan1 | 1 | 15,00 | 56 |
| 12 | Plan1 | 2 | 13,50 | 56 |
| 13 | Plan1 | 3 | 11,50 | 56 |
+----------+---------+-----------+-------+---------+
我该怎么做?
答案 0 :(得分:0)
您可以使用row_number()
来枚举受抚养人,然后使用join
:
select d.*, p.price
from (select d.*, row_number() over (partition by primary_id order by id_dependent) as seqnum
from dependents d
) d left join
price p
on p.dependent = d.seqnum and p.plan_id = 56;
在早期版本的MySQL中,您可以使用变量:
select d.*, p.price
from (select d.*,
(@rn := if(@p = d.primary_id, @rn + 1,
if(@p := d.primary_id, 1, 1)
)
) as seqnum
from (select d.* from dependents d order by primary_id, id_dependent) d cross join
(select @p := -1, @rn := 0) params
) d left join
price p
on p.dependent = d.seqnum and p.plan_id = 56;
有关变量使用的注意事项:
order by
在子查询中;在某些版本的MySQL中是必需的。变量和order by
不能总是一起玩。答案 1 :(得分:0)
这适用于mysql 5.6和5.7
Select d.`id_dependent`, d.`name`, d.`number`, d.`primary_id`, p.`Value`
From (
SELECT d.*,
if (@primid = primary_id,@curRank := @curRank + 1,@curRank := 1) AS rank,
@primid := primary_id
FROM Dependent d, (SELECT @curRank := 0) r , (SELECT @primid := 0) s
ORDER BY primary_id,id_dependent) d
left join price p on p.Dependent = d.rank
Order by d.`id_dependent`;
产生的结果
id_dependent name number primary_id Value
51 Carlos 956585 2 15,00
52 João 985868 2 13,50
53 Jaime 985868 2 11,50
54 Evan 985847 3 15,00
55 Kaus 584788 3 13,50