我们有一个产品明智的时间花费表,例如
--------------------------------------------------
ID| Timespent | Userid | productID |
--------------------------------------------------
1 | 12333 | 420 | 223
2 | 3647 | 424 | 423
3 | 333 | 424 | 823
4 | 1333 | 654 | 283
--------------------------------------------------
上表中有多个条目
我们还有另一个表,其中包含产品和标签映射
--------------------------------------------------
product_id | tag_id |
--------------------------------------------------
1 | 4352
823 | 43
823 | 654
423 | 4352
--------------------------------------------------
我们还有另一个带有标签名称的表
--------------------------------------------------
tag | tag_name |
--------------------------------------------------
1 | NEWS
823 | Sports
223 | cricket
423 | football
--------------------------------------------------
例如,我想根据标签和用户的实际情况获取花费的时间总和
用户ID应该不同,花费的总时间将是花费的时间
--------------------------------------------------
user_id | tag_name | total_time_spend
--------------------------------------------------
823 | football | 324237462
722 | cricket | 324237462
839 | new | 324237462
923 | USA news | 324237462
23 | MODI | 324237462
--------------------------------------------------
答案 0 :(得分:1)
使用联接和相关的子查询
select t.* from (
Select p.userid, tn.name,sum(p.timespent) as total
From product p join tagmapping tm
on p.productid=tm.product_id
Join tagname tn on tm.tag_id=tn.tag
Group by p.userid,tn.name
) t where total=
select max(total) from
(
Select p.userid, tn.name,sum(p.timespent) as total
From product p join tagmapping tm
on p.productid=tm.product_id
Join tagname tn on tm.tag_id=tn.tag
Group by p.userid,tn.name
) a where a.userid=t.userid