mysql – SQL连接,用于将子表中的值与子表值连接为单行中的不同列
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了mysql – SQL连接,用于将子表中的值与子表值连接为单行中的不同列,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2147字,纯文字阅读大概需要4分钟。
内容图文
![mysql – SQL连接,用于将子表中的值与子表值连接为单行中的不同列](/upload/InfoBanner/zyjiaocheng/903/e96341f34a144610ae1f9f24b18a197b.jpg)
我有一个survey_datas表包含这样的数据
survey_data_id | title
1 | Paul
3 | Anna
4 | Alan
另一个表project_playlist_indexes包含这样的数据
survey_id |survey_data_id | favorite
1 | 1 | 22.10
2 | 1 | 24.00
3 | 3 | 12.00
我想将survey_datas表与project_playlist_indexes表一起使用,以便project_playlist_indexes表中包含的与survey_datas表相同的survey_data_id的值应该是最喜欢的time1,最喜欢的时间2,…最喜欢的时间n,我想得到的结果表是像这样
survey_data_id |title | favorite_time1 | favorite_time2
1 | paul | 22.10 |24.00
3 | anna | 12.00 | null
4 | alan | null | null
目前我正在使用该查询
SELECT s.*,GROUP_CONCAT(pi.favorite) ,pi.*
FROM survey_datas s
LEFT JOIN project_playlist_indexes pi
ON pi.survey_data_id = s.survey_data_id
GROUP BY pi.survey_data_id
但最喜欢的值是进入一个字段,我希望它在不同的列中.我怎样才能做到这一点
解决方法:
您可以通过执行动态SQL查询来完成此操作.我所做的是,首先根据survey_data_id列给出一个行号.然后通过survey_data_id选择每个行编号项作为每个列组.不知道代码的效率如何.
询问
set @query = null;
select
group_concat(distinct
concat(
'max(case when `rn` = ',
`rn`,
' then `favorite` end) as `favorite', `rn` , '`'
)
) into @query
from (
select `survey_id`, `survey_data_id`, `favorite`, (
case `survey_data_id` when @curA
then @curRow := @curRow + 1
else @curRow := 1 and @curA := `survey_data_id` end
) as `rn`
from `project_playlist_indexes` t,
(select @curRow := 0, @curA := '') r
order by `survey_data_id`, `survey_data_id`
) t;
set @query = concat('select t2.`survey_data_id`, t2.`title`,',
@query,
' from (select `survey_id`, `survey_data_id`, `favorite`, (
case `survey_data_id` when @curA
then @curRow := @curRow + 1
else @curRow := 1 and @curA := `survey_data_id` end
) as `rn`
from `project_playlist_indexes` t,
(select @curRow := 0, @curA := '''') r
order by `survey_data_id`, `survey_data_id`) t1
right join `survey_datas` t2
on t1.survey_data_id = t2.`survey_data_id`
group by t1.`survey_data_id`
order by t2.`survey_data_id`;'
);
prepare stmt from @query;
execute stmt;
deallocate prepare stmt;
内容总结
以上是互联网集市为您收集整理的mysql – SQL连接,用于将子表中的值与子表值连接为单行中的不同列全部内容,希望文章能够帮你解决mysql – SQL连接,用于将子表中的值与子表值连接为单行中的不同列所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。