簡體   English   中英

查詢多行成單行

[英]Query Multiple Rows into a single row

上一天,我遇到了一個要求,我必須與非工程團隊共享為實體設置的所有配置-這意味着我需要一個Excel / CSV。

我的表結構看起來像

id | entity_id | config_id | value | is_active

我的csv結果應該類似於:

Entity_id, config1_value, config2_value, config3_value ... 

我確實得到了輸出,但是沒有很好的方法。 我對我所采用的方法不滿意。 我的查詢就像

SELECT entity_id,
group_concat(if(config_id = 1, value, "")) as config1_value,
group_concat(if(config_id = 2, value, "")) as config2_value,
group_concat(if(config_id = 3, value, "")) as config3_value,
...
FROM table_name
WHERE is_active = 1
AND config_id in (1,2,3...)
group by entity_id;

該查詢工作正常,並且由於該表仍具有少於10萬條記錄,因此查詢速度也很快。 如您所見,如果我需要添加或刪除新的配置鍵來報告,則必須至少更改2行。 我正在運行MySQL 5.1。 有什么更好的解決方案?

在這里您可以找到: http : //sqlfiddle.com/#!2/b266c2/17

與您所做的沒有太大不同。 聽起來您正在尋找pivot tablecrosstab report

另請參閱以下答案: https : //stackoverflow.com/a/8922865/3112803

但是,如果您想動態地進行操作,而不必繼續將這些列max(if(config_id = 1, value, "")) as config1_value,添加/刪除max(if(config_id = 1, value, "")) as config1_value,那么請看一下本文“自動化數據透視表查詢” -http://www.artfulsoftware.com/infotree/qrytip.php?id=523

我懷疑該問題缺少某些實體的配置值。 一種方法是為每個實體的每個配置值創建一行:

SELECT e.entity_id,
       group_concat(coalesce(t.value, '') order by c.config_id) as values
FROM (select distinct entity_id where is_active = 1 from table_name) e cross join
     (select 1 as config_id union all select 2 union all select 3
     ) c left outer join
     table_name t
     on t.entity_id = e.entity_id and t.config_id = t.config_id
WHERE t.is_active = 1
group by entity_id;

另一種方法是您使用的路徑,其中每個值都放在單獨的列中。 為此,請使用max()而不是group_concat()

SELECT entity_id,
       max(if(config_id = 1, value, NULL)) as config1_value,
       max(if(config_id = 2, value, NULL)) as config2_value,
       max(if(config_id = 3, value, NULL)) as config3_value,
...
FROM table_name
WHERE is_active = 1
AND config_id in (1,2,3...)
group by entity_id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM