0

I have a table called idcards with a foreign key on the id of the table reservations. Then I have a table photos that has a foreign key on the id in table idcards.

I want to select all from idcards where the reservation id is a certain value, plus the photos that are attached to this idcard.

This is what I have so far, but it obviously selects only one photo per idcard:

SELECT i.*, p.photo 
FROM idcards AS i 
INNER JOIN photos AS p 
    ON (i.id=p.iId) 
WHERE i.resId = 1

How can I make it so the idcards that I get have an array with all the photos ?

4
  • What does "array" have to do with your question? MySQL doesn't support arrays. Commented Feb 12, 2021 at 13:02
  • 2
    'obviously selects only one photo per idcard:' - not obvious to me , I would have said this results in 1 row per photo..Please add sample data and expected outcome as text to the question. Commented Feb 12, 2021 at 13:08
  • @P.Salmon youre right, it does, thank you :) Commented Feb 12, 2021 at 13:36
  • I suspect you are looking for group_concat dev.mysql.com/doc/refman/8.0/en/… Commented Feb 12, 2021 at 14:07

1 Answer 1

2

If you want only the field photo from the table photos, you can group them in an array, associating it to the idcard, with a query like the following:

SELECT i.*, JSON_ARRAYAGG(p.photo) FROM idcards AS i LEFT JOIN photos AS p ON (i.id=p.iId) WHERE i.resId = 1 GROUP BY i.id;

Or the following, to return the photos in a same field, separed by a comma:

SELECT i.*, GROUP_CONCAT(p.photo) FROM idcards AS i LEFT JOIN photos AS p ON (i.id=p.iId) WHERE i.resId = 1 GROUP BY i.id;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.