我有一张桌子,记录如下
------------------------------------------------
id |m_id | primary | secondary | Duration
------------------------------------------------
1 | 1 | 100 | 80 | 12m
------------------------------------------------
2 | 1 | 50 | 40 | 6m
------------------------------------------------
3 | 2 | 300 | 150 | 12m
------------------------------------------------
4 | 2 | 150 | 70 | 6m
------------------------------------------------
5 | 3 | 500 | 300 | 12m
------------------------------------------------
6 | 3 | 300 | 200 | 6m
我需要这样的输出。请注意,这里是按月显示数据。
--------------------------------------------
id |m_id | primary | secondary
| | 12m |6m |12m |6m
--------------------------------------------
1 |1 |100 |50 | 80 |40
--------------------------------------------
2 |2 |300 |150 | 150 |70
--------------------------------------------
3 |3 |500 |300 | 300 |200
但是我得到的输出是(我还没有添加金额)
--------------------------------------------
id |m_id | primary | secondary
| | 12m |6m |12m |6m
--------------------------------------------
1 |1 |
--------------------------------------------
1 |1 |
--------------------------------------------
2 |1 |
--------------------------------------------
3 |2 |
--------------------------------------------
3 |2 |
--------------------------------------------
4 |2 |
我尝试查询
SELECT *
FROM `tbl_activityFees2` as `t1`
JOIN `tbl_activityFees2` as `t2` ON `t2`.`m_id`=`t1`.`m_id`
JOIN `activity_name` ON `activity_name`.`m_id`=`t1`.`m_id`
WHERE `t1`.`is_feesActive` = 1
AND `t2`.`is_feesActive` = 1
AND `t1`.`Duration` = '12m'
OR `t2`.`Duration` = '6m'
您能在这个问题上帮助我吗?
答案 0 :(得分:1)
您可以按最大逻辑分组,然后按如下所示与主表联接
select `t1`.id
,grouped_data.*
from(
SELECT `t1`.m_id
,max(case when `t1`.duration='12m' then primary end) as primary_12m
,max(case when `t1`.duration='6m' then primary end) as primary_6m
,max(case when `t1`.duration='12m' then secondary end) as secondary_12m
,max(case when `t1`.duration='6m' then secondary end) as secondary_6m
FROM `tbl_activityFees2` as `t1`
WHERE `t1`.`is_feesActive` = 1
GROUP BY `t1`.m_id
) grouped_data
JOIN `tbl_activityFees2` as `t1`
on t1.m_id=grouped_data.m_id
答案 1 :(得分:0)
我将执行完全外部联接。由于MySQL不支持完全外部联接,因此您需要通过UNION
设置为OUTER JOIN
s来模拟它们,如下所示:
select
coalesce(t1.m_id, 2.m_id) as m_id,
t2.primary as primary_12m,
t1.primary as primary_6m,
t2.secondary as secondary_12m,
t1.secondary as secondary_6m
from tbl_activityFees2 t1
left join tbl_activityFees2 t2
on t1.m_id = t2.m_id
and t1.duration = '6m'
and t2.duration = '12m'
and t1.is_feesActive = 1
and t2.is_feesActive = 1
union
select
coalesce(t1.m_id, 2.m_id) as m_id,
t2.primary as primary_12m,
t1.primary as primary_6m,
t2.secondary as secondary_12m,
t1.secondary as secondary_6m
from tbl_activityFees2 t2
left join tbl_activityFees2 t1
on t1.m_id = t2.m_id
and t1.duration = '6m'
and t2.duration = '12m'
and t1.is_feesActive = 1
and t2.is_feesActive = 1