MYSQL 查询以下内容
MYSQL Query for the below
我的连接查询没有按预期返回结果。下面是 table 结构、使用的查询、结果和预期结果
Table答:
Id Name Token
1 A abcdef
2 B think
3. C Bxjscmsdnj
Table乙:
id TableA_id configKey configValue
1 2 pmt ins
2 2 vat gas
3 1 vat nnnb
4 1 pmt mc
5 3 vat nhu
6 3 pmt nnu
7 2 hit bxhsjab
下面是我使用的查询:
SELECT A.Token,
A.Name,
CASE
WHEN B.configKey = 'pmt’ THEN B.configValue
ELSE ''
END AS ‘PMT’,
CASE
WHEN B.configKey = ‘vat’ THEN B.configValue
ELSE ''
END AS ‘VAT’
FROM TABLEA A
INNER JOIN TABLEB B ON A.Id = B.TableA_id
WHERE B.configKey IN (‘PMT’, ‘VAT’)
ORDER BY A.id DESC;
结果:
Token Name PMT VAT
1 A nnnb
1 A mc
2 B gas
2 B ins
预期结果:
Token Name PMT VAT
1 A mc nnnb
2 B ins gas
您需要条件聚合。首先,添加一个 group by
子句,将具有相同 id
和 name
的行组合在一起;然后,将 case
表达式包装在聚合函数中,例如 max()
:
select
a.id,
a.name,
max(case when b.configkey = 'pmt' then b.configvalue end) pmt,
max(case when b.configkey = 'vat' then b.configvalue end) vat
from tablea a
inner join tableb b on a.id = b.tablea_id
where b.configkey in ('pmt', 'vat')
group by a.id, a.name
order by a.id desc;
我的连接查询没有按预期返回结果。下面是 table 结构、使用的查询、结果和预期结果
Table答:
Id Name Token
1 A abcdef
2 B think
3. C Bxjscmsdnj
Table乙:
id TableA_id configKey configValue
1 2 pmt ins
2 2 vat gas
3 1 vat nnnb
4 1 pmt mc
5 3 vat nhu
6 3 pmt nnu
7 2 hit bxhsjab
下面是我使用的查询:
SELECT A.Token,
A.Name,
CASE
WHEN B.configKey = 'pmt’ THEN B.configValue
ELSE ''
END AS ‘PMT’,
CASE
WHEN B.configKey = ‘vat’ THEN B.configValue
ELSE ''
END AS ‘VAT’
FROM TABLEA A
INNER JOIN TABLEB B ON A.Id = B.TableA_id
WHERE B.configKey IN (‘PMT’, ‘VAT’)
ORDER BY A.id DESC;
结果:
Token Name PMT VAT
1 A nnnb
1 A mc
2 B gas
2 B ins
预期结果:
Token Name PMT VAT
1 A mc nnnb
2 B ins gas
您需要条件聚合。首先,添加一个 group by
子句,将具有相同 id
和 name
的行组合在一起;然后,将 case
表达式包装在聚合函数中,例如 max()
:
select
a.id,
a.name,
max(case when b.configkey = 'pmt' then b.configvalue end) pmt,
max(case when b.configkey = 'vat' then b.configvalue end) vat
from tablea a
inner join tableb b on a.id = b.tablea_id
where b.configkey in ('pmt', 'vat')
group by a.id, a.name
order by a.id desc;