gpt4 book ai didi

mysql - 连接表并转置列和行

转载 作者:行者123 更新时间:2023-11-29 01:22:52 24 4
gpt4 key购买 nike

我有一个看起来像这样的表,叫做 survey_1:

================================================
|id | token | 1X2X1 | 1X2X2 |
=====+========+===============+================|
| 1 | 1 | YES | Justin Beiber |
|----+--------+---------------+----------------|
| 2 | 1 | YES | Britney Spears |
|----+--------+---------------+----------------|

注意:1X2X1代表-survey-id X group-id X question-id

我有另一个名为 survey_questions 的表:

===============================================================
|sid | gid | qid | question |
=====+========+===============+===============================|
| 1 | 2 | 1 | Do you listen to music? |
|----+--------+-----------------------------------------------|
| 1 | 2 | 2 | Who is your favorite music artists? |
|----+--------+-----------------------------------------------|

sid (survey-id)、gid (group-id) 和 qid(question-id) 定义了这个表中的特定问题

我需要一个能给我这样结​​果的查询:

======================================================
| Question | Answer |
=========+===========+===============================|
| Do you listen to music? | YES |
|----------------------------------------------------|
| Who is your favorite music artists? | Justin Beiber|
|----------------------------------------------------|

注意:我的数据库包含数千个这样的列,因此编辑每个调查以完全匹配这种格式将非常耗时。

谁能帮忙解决这个问题?谢谢

最佳答案

你能改变表架构吗?因为第一个表 survey_1 最好写成每个答案一行,每行包含另一个表的整个键。像这样(添加自己的索引)

create table survey_1 (
id int,
token int,
sid int,
gid int,
qid int,
answer varchar(255)
)

比数据会是

------------------------------------------
| 1 | 1 | 1 | 2 | 1 | "YES" |
| 1 | 1 | 1 | 2 | 2 | "Justin Beiber" |
| 2 | 1 | 1 | 2 | 1 | "YES" |
| 2 | 1 | 1 | 2 | 2 | "Britney Spears" |
------------------------------------------

它会更容易使用,而且通常会是更好的设计。

这是它的样子 http://sqlfiddle.com/#!2/4f1ca/2

关于mysql - 连接表并转置列和行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12962000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com