将multy行转换为列

时间:2016-04-07 08:16:51

标签: mysql sql

我试图从MySQL数据库中检索数据。 表格的结构(var mainForm = $("#mainForm"); mainForm.on("submit", function(){ var gitHubSearch = "https://api.github.com/search/repositories?q=jquery_language:javascript&sort=starts" jQuery.support.cors = true; $.get(gitHubSearch) .success(function(r) { console.log(r.items.length); displayResults(r.items); }) .fail(function(err) { console.log("Failed to query GitHub"); resultList.text("The API Call has failed."); }) .done(function() { console.log("API Call completed"); }); }); )有:

Tab_1

如您所见,这实际上是订单详情信息。

我想将键列转换为实际列,将值转换为此列的值。 意思是:

id   key      value
 1   address   xyz
 1   post_code 120
 1   country   CA

id address post_code country ------------------------------------ 1 xyz 120 CA 是此订单的关键。

MySQL中的表无法更改。它是我们使用的密切系统的一部分(WordPress插件)我只想编写一个从中获取一些数据的查询......

我的目标是在连接中使用它,以便更容易获取数据:

id=1

它应该给:

Select x.address ,x.post_code, x.country
from orders
join (...) as x using (order_id=id)
where order_id=1

正如你所看到的,它假设得到x的所有字段,即地址,post_code,country等。 联接中的 address post_code country ------------------------------------ xyz 120 CA 是我需要将...转换为连接的可读结构的查询。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

执行GROUP BY,对不同的密钥类型使用CASE表达式:

select id,
       max(case when key = 'address' then value end) as address,
       max(case when key = 'post_code' then value end) as post_code,
       max(case when key = 'country' then value end) as country
from orders
group by id

答案 1 :(得分:0)

您只能使用4个选项:

SELECT id, (SELECT value FROM Tab_1 WHERE id = 1 AND `key` = 'address') AS address,
(SELECT value FROM Tab_1 WHERE id = 1 AND `key` = 'post_code') AS post_code,
(SELECT value FROM Tab_1 WHERE id = 1 AND `key` = 'country') AS country FROM Tab_1
GROUP BY id;