[英]Transpose dynamic rows into columns
I have two tables: one is programs
and the other one is bookprograms
. 我有两个表:一个是
programs
,另一个是bookprograms
。 The programs
table is where you get the program name. programs
表是您获得程序名称的地方。 The rows in this table can be added or edited. 可以添加或编辑此表中的行。
I used the query below but it doesn't reflect if there is a new program: 我在下面使用了查询,但没有反映出是否有新程序:
SELECT MAX(IF(programs = 'cla', title, NULL)) cla,
MAX(IF(programs = 'csm', title, NULL)) csm
FROM bookprograms
GROUP BY title
The structure of the first table. 第一个表的结构。
╦════════════╦═════════════╗
║ ID ║ Programs ║
╬════════════╬═════════════╣
║ 1 ║ cla ║
║ 2 ║ csm ║
╩════════════╩═════════════╝
The second table is where I store the books and the program that corresponds to it. 第二张表是我存储书籍和与其对应的程序的地方。
╦════════════╦═════════════╗
║ Title ║ Programs ║
╬════════════╬═════════════╣
║ title1 ║ cla ║
║ title2 ║ csm ║
║ title3 ║ cla ║
╩════════════╩═════════════╝
How would I come up with this result? 我将如何得出这个结果?
╦════════════╦═════════════╗
║ cla ║ csm ║
╬════════════╬═════════════╣
║ title1 ║ title ║
║ title3 ║ ║
╩════════════╩═════════════╝
This query returns the data you need but not quite in the format you want it: 此查询返回所需的数据,但格式不完全符合所需格式:
SELECT programs, GROUP_CONCAT(title) AS titles
FROM bookprograms
GROUP BY programs
It returns: 它返回:
programs | titles
----------+---------------
cla | title1,title3
cls | title2
In the client code you can morph this into the structure you need. 在客户端代码中,您可以将其变形为所需的结构。 The value of the header cell is returned in field
programs
. 头单元的值在现场
programs
返回。 Split the value of field title
by comma ( ,
) and you have the data cells for the rest of the column. 用逗号(
,
)分隔字段title
的值,您将获得该列其余部分的数据单元格。 Repeat for each row from the result set to get all the columns of your desired table. 对结果集中的每一行重复此操作,以获取所需表的所有列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.