为了从 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
结果是:
| TEAMA | A | B | C | D | E |
------------------------------
| A | 0 | 2 | 0 | 8 | 0 |
| B | 0 | 0 | 0 | 0 | 0 |
| C | -2 | 0 | 0 | 0 | 0 |