准备好的声明:如何加入标题

时间:2013-02-08 19:33:15

标签: mysql join prepared-statement pivot

我有2个表,我想在预备语句中加入标题和第一列。我已经设法加入该列,但如何加入标题?

表1:

  ID |Name 
----------
  1  |  A  
  2  |  B  
  3  |  C  
  4  |  D  
  5  |  E  

表2:

TeamA|TeamB|Won|Lost
--------------------
  1  |  2  | 5 | 3
  1  |  3  | 2 | 4
  1  |  4  | 9 | 1
  2  |  5  | 5 | 5
  3  |  1  | 2 | 4

结果矩阵:

     |  A | B |  C | D | E
----------------------------
  A  |  0 | 2 | -2 | 8 | 0
  B  |  0 | 0 |  0 | 0 | 0
  C  | -2 | 0 |  0 | 0 | 0

SQL Fiddle

1 个答案:

答案 0 :(得分:0)

为了从ids中获取团队名称,您必须两次加入桌面。

如果您知道所有值,则代码的静态版本为:

select a.name teamA,
  max(case when b.name = 'A' then won - lost else 0 end) as A,
  max(case when b.name = 'B' then won - lost else 0 end) as B,
  max(case when b.name = 'C' then won - lost else 0 end) as C,
  max(case when b.name = 'D' then won - lost else 0 end) as D,
  max(case when b.name = 'E' then won - lost else 0 end) as E
from yourtable t
left join teams a
  on t.teama = a.id
left join teams b
  on t.teamb = b.id
group by a.name;

请参阅SQL Fiddle with Demo

然后,如果您使用预准备语句动态创建它,则代码将为:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN TeamB = ''',
      TeamB,
      ''' THEN won - lost else 0 END) AS `',
      TeamB, '`'
    )
  ) INTO @sql
from
(
  select a.name TeamA,
    b.name TeamB,
    t.won,
    t.lost
  from yourtable t
  left join teams a
    on t.teama = a.id
  left join teams b
    on t.teamb = b.id
  order by teamb
) x;

SET @sql 
  = CONCAT('SELECT TeamA, ', @sql, ' 
           from
           (
             select a.name TeamA,
              b.name TeamB,
              t.won,
              t.lost
            from yourtable t
            left join teams a
              on t.teama = a.id
            left join teams b
              on t.teamb = b.id
           ) s
           group by TeamA');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

请参阅SQL Fiddle with Demo

结果是:

| TEAMA |  A | B | C | D | E |
------------------------------
|     A |  0 | 2 | 0 | 8 | 0 |
|     B |  0 | 0 | 0 | 0 | 0 |
|     C | -2 | 0 | 0 | 0 | 0 |