slowie
slowie

Reputation: 51

one to many mysql query

Hey guys sorry to ask but i need help with this query please I've been messing around with different solutions but so far have not been able to solve it myself.

I have 4 tables called customer, figures, notes and lender. They all have a field called reference, which is what I'm using to link them together. Customer is the primary table and there is only one record in the figures table for each customer so i can do:

select * From customer, figures
where customer.reference = figures.reference

However, there may be multiple notes and lender records for each customer. How can I link them to show only one record?

Ideally, there would be a way to display it as:

reference, name, figures, lender 1, lender 2, note 1, note 2, note 3

Upvotes: 1

Views: 370

Answers (1)

Nikoloff
Nikoloff

Reputation: 4160

You can use group_concat():

SELECT customer.reference, customer.name, figures.name, 
GROUP_CONCAT(DISTINCT lender.name), 
GROUP_CONCAT(DISTINCT notes.name) 
FROM customer 
JOIN figures ON figures.reference = customer.reference 
LEFT JOIN lender ON lender.reference = customer.reference 
LEFT JOIN notes ON notes.reference = customer.reference 
GROUP BY customer.reference;

Assuming that each of the tables has a field name, you should change it to whatever your columns are.

Upvotes: 1

Related Questions