简体   繁体   English

MySQL在同一行中选择数据

[英]Mysql select data in same row

I'm really confused about this query. 我真的很困惑这个查询。 I would like to get all the data for one context in one row. 我想在一行中获取一个上下文的所有数据。 I really don't know how to do that. 我真的不知道该怎么做。 Here's the tables's sample. 这是表格的示例。

data (table)                               io(table)
IDData    IDIO   ReadVal   No              IDIO   IDContext
1          io1     12       1              io1       c1     
2          io2     12.5     2              io2       c1 
3          io3     11       3              io3       c1 
4          io4     12.2     1              io4       c2  
5          io5     10       2              io5       c2  
6          io6     10.9     3              io6       c2

I would like to get this result 我想得到这个结果

IDContext    IO-1   IO-2   IO-3
   c1         12    12.5    11
   c2        12.2    10    10.9

I've tried to do this in a loop to print in a table and it works, but I would like to do it in a query so it will be faster. 我试图在循环中执行此操作以在表中进行打印,并且可以正常工作,但是我想在查询中执行此操作,这样会更快。

Actually, my query looks like that : 实际上,我的查询如下所示:

SELECT IDContext, IDInput, ReadVal
FROM data
LEFT JOIN io ON io.IDIO = data.IDIO
ORDER BY IDContext, No

Is this possible to get that result in one single query? 是否可以通过一个查询获得该结果?

You can do this with conditional aggregation: 您可以使用条件聚合来做到这一点:

SELECT IDContext,
       MAX(CASE WHEN no = 1 THEN data.ReadVal END) as io1,
       MAX(CASE WHEN no = 2 THEN data.ReadVal END) as io2,
       MAX(CASE WHEN no = 3 THEN data.ReadVal END) as io3
FROM data LEFT JOIN
     io
     ON io.IDIO = data.IDIO
GROUP BY IDContext
ORDER BY IDContext;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM