简体   繁体   中英

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

Then join on table B and concatenate all the values that match a specific ID from Table.

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

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.

I only seem to get results where a record exists in both tables.

You are describing a 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.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM