[英]mysql left join with group_concat - only shows a single result
So I am not sure if I am taking the right approach but here is what I am after: I need to get all the records from table A所以我不确定我是否采取了正确的方法,但这就是我所追求的:我需要从表 A 中获取所有记录
Then join on table B and concatenate all the values that match a specific ID from Table.然后加入表 B 并连接与表中特定 ID 匹配的所有值。
What I am noticing with my query below, is that I only get results where there is a record in Table B - I want to be able to display a NULL value in my result set if there is no corresponding value in Table A我在下面的查询中注意到的是,我只得到表 B 中有记录的结果 - 如果表 A 中没有相应的值,我希望能够在我的结果集中显示 NULL 值
SELECT Account.AccountID, AccountOpenedDate, AccountStatus, GROUP_CONCAT(Expense.ExpenseType SEPARATOR ':') AS Expense FROM Account
JOIN Expense ON Account.AccountID=Expense.AccountID
GROUP BY MONTH(DATE(AccountOpenedDate)), Account.AccountID
ORDER BY Account.AccountID ASC;
I want to return all accounts and account status and opened date Then if Expense has a value for that row display those values concatenated with ":" as a separator.我想返回所有帐户和帐户状态以及打开日期然后如果 Expense 具有该行的值,则显示那些与“:”连接的值作为分隔符。
I only seem to get results where a record exists in both tables.我似乎只在两个表中都存在记录的情况下得到结果。
You are describing a left join
:您正在描述left join
:
select
a.accountID,
a.accountOpenedDate,
a.accountStatus,
group_concat(e.expenseType separator ':') as expense
from account a
left join expense e on e.accountID = a.accountID
group by a.accountID
order by a.accountID
I also don't see the point for expression MONTH(DATE(AccountOpenedDate))
in the GROUP BY
clause: you seem to want one row per account, so this seems irrelevant.我也没有看到GROUP BY
子句中表达式MONTH(DATE(AccountOpenedDate))
的意义:您似乎希望每个帐户一行,所以这似乎无关紧要。
The above query works under the assumption that accountID
is the primary key of table account
: other columns from the same column are functionaly dependent on the primary key, so you do not need to list them in the group by
clause.上面的查询假设accountID
是表account
的主键:同一列中的其他列在功能上依赖于主键,因此您不需要在group by
子句中列出它们。 You could also write this as:你也可以这样写:
select
a.accountID,
a.accountOpenedDate,
a.accountStatus,
group_concat(e.expenseType separator ':') as expense
from account a
left join expense e on e.accountID = a.accountID
group by a.accountID, a.accountOpenedDate, a.accountStatus
order by a.accountID
Side notes:旁注:
table aliases make the query easier to write and read表别名使查询更易于编写和阅读
in a multi-table query, all columns should be qualified (prefixed) with the (alias of the) table they belong to在多表查询中,所有列都应使用它们所属的表(别名)进行限定(前缀)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.