【问题标题】:how to query out mysql record which store values in one column如何查询出存储在一列中的值的mysql记录
【发布时间】:2015-03-04 00:21:28
【问题描述】:

我使用 joomla 的 breezingform 创建 web 表单,将用户输入记录存储在数据库中,如下所示:

forms_records

id  | form  | name          
24    19       kpi          
25    19       kpi  

forms_subrecords

id   | element  | record    | description  |  value  | type
101     406        24          month         2015-01   calendar
102     407        24          east          30%       text
103     408        24          south         35%       text
104     409        24          north         50%       text
105     410        24          west          25%       text
106     406        25          month         2015-02   calendar
107     407        25          east          45%       text
108     408        25          south         35%       text
109     409        25          north         15%       text
110     410        25          west          5%        text

我试过这样做: 1. 先获取记录id

SELECT id FROM forms_records WHERE form='19'
  1. 获取子记录值
SELECT s.value 
from forms_subrecords AS s 
WHERE s.record 
  IN (SELECT id FROM forms_records WHERE form='19')

结果是10行一列,

2015-01
30%
35%
50%
25%
2015-02
45%
35%
15%
5%

但我想要的是 2 行 5 列:

2015-01 30% 35% 50% 25% 
2015-02 45% 35% 15% 5%  

任何人都可以帮助或提供一些提示?

【问题讨论】:

标签: mysql


【解决方案1】:

也许 Pivot 会起作用。希望能帮助到你。 http://en.wikibooks.org/wiki/MySQL/Pivot_table

【讨论】:

    【解决方案2】:

    您可以使用条件 case 表达式和聚合 max 函数来执行此操作:

    SELECT 
      max(case when s.description = 'month' then s.value end) col1,
      max(case when s.description = 'east'  then s.value end) col2,
      max(case when s.description = 'south' then s.value end) col3,
      max(case when s.description = 'north' then s.value end) col4,
      max(case when s.description = 'west'  then s.value end) col5
    FROM forms_subrecords AS s 
    WHERE s.record 
      IN (SELECT id FROM forms_records WHERE form='19')
    GROUP BY 
      record
    

    SQL Fiddle 的示例给出了以下输出:

    |    COL1 | COL2 | COL3 | COL4 | COL5 |
    |---------|------|------|------|------|
    | 2015-01 |  30% |  35% |  50% |  25% |
    | 2015-02 |  45% |  35% |  15% |   5% |
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 2021-10-14
      • 2013-06-28
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      相关资源
      最近更新 更多