我有像这样的mysql查询
SET @sql = NULL;
SELECT
GROUP_CONCAT(
'fvalue AS ',x.name
) INTO @sql
from reimbursment x
LEFT JOIN reimbursment_limit y
ON y.acc_code = x.acc_code;
SET @sql = CONCAT('SELECT b.firstname, ', @sql, ' from user b
left join reimbursment_limit c
on b.id = c.user_id
left join reimbursment d
on c.acc_code = d.acc_code
group by b.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
和这样的表,
用户
id nip firstname
1 123456 AAAAA
2 999999 BBBBB
reimbursment
id acc_code name
1 22002 Dentis
2 22004 Allowance
报销限额
id user_id acc_code fvalue
1 1 22002 500000
2 1 22004 700000
和结果,像这样
firstname Dentis Allowance
AAAAA 500000 500000
BBBBB null null
正确的结果,必须
firstname Dentis Allowance
AAAAA 500000 700000
BBBBB null null
这个查询是workig,但是没有给出正确的结果,其中用户AAAAA的余量必须为700000,如何修复结果?我已尝试任何但仍然没有给出正确的结果。
谢谢
答案 0 :(得分:0)
问题在于加入小组
SET @sql = CONCAT('SELECT b.firstname, ', @sql, ' from user b
left join reimbursement c -- swapped join clause
on b.id = c.user_id
left join reimbursment_limit d
on c.acc_code = d.acc_code'); -- removed group by