简体   繁体   English

将具有不同值的行合并为一行

[英]Merge rows with different values into a single row

Query that I'm using我正在使用的查询

SELECT v.*,  if( up.upload_key = 'send', up.upload_value, 0 ) AS send,  
    if( up.upload_key = 'host', up.upload_value, 0 ) AS host, 
     if( up.upload_key = 'upload_id', up.upload_value, 0 ) AS upload_id 
FROM TableInit v JOIN TableName up ON up.video_id =  v.id_video;

The return of the query is this查询的返回是这样的

| id_video | titulo | desc | send | host |    upload_id |
|----------|--------|------|------|------|--------------|
|        6 |  Title | Desc |    0 |  cnn |            0 |
|        6 |  Title | Desc |    0 |    0 |            0 |
|        6 |  Title | Desc |    0 |    0 | sHGN-tSNvJYs |

The return I need is this:我需要的回报是这样的:

| id_video | titulo | desc | send | host |   upload_id |
|----------|--------|------|------|------|-------------|
|        6 |  Title | Desc |    0 |  cnn |sHGN-tSNvJYs |

If I use GROUP BY I have this return which is only the value of the first row and not the other如果我使用 GROUP BY 我有这个返回值,它只是第一行的值而不是另一行的值

| id_video | titulo | desc | send | host | upload_id |
|----------|--------|------|------|------|-----------|
|        6 |  Title | Desc |    0 |  cnn |         0 |

SQLFiddle SQLFiddle

This should do the job :这应该可以完成这项工作:

SELECT v.*,  if( up.upload_key = 'send', up.upload_value, 0 ) AS send,  
    MAX(if( up.upload_key = 'host', up.upload_value, null )) AS host, 
     MAX(if( up.upload_key = 'upload_id', up.upload_value, null )) AS upload_id 
FROM TableInit v JOIN TableName up ON up.video_id =  v.id_video GROUP BY id_video;

I just added MAX function to select only the max value of the columns host and upload_id.我刚刚添加了MAX函数来仅选择列 host 和 upload_id 的最大值。

The returned result :返回的结果:

+----------+--------+------+------+------+--------------+
| id_video | titulo | desc | send | host | upload_id    |
+----------+--------+------+------+------+--------------+
|        6 | Title  | Desc | 0    | cnn  | sHGN-tSNvJYs |
+----------+--------+------+------+------+--------------+

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

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