First of all, I am pretty new to MySQL. I am currently stuck with the following query. I have several tables that have relations between each other. Every user can create multiple projects. Every project can have one attachment, multiple attachments (images) or no attachment at all. Every project only has one user.
Table users
| id | username | avatar |
|---|---|---|
| 1 | user1 | image1.png |
| 2 | user2 | image2.png |
Table projects
| id | title | user_id |
|---|---|---|
| 1 | project1 | 1 |
| 2 | project2 | 1 |
Table images
| id | image_name | project_id |
|---|---|---|
| 1 | attachment1.png | 1 |
| 2 | attachment2.png | 1 |
My current query:
SELECT
projects.id,
projects.title,
users.username,
users.avatar,
images.image_name
FROM
users,
projects,
images
WHERE
users.id = user_id
AND projects.id = project_id
This gives me the following output:
| id | title | username | avatar | image_name |
|---|---|---|---|---|
| 1 | project1 | user1 | image1.png | attachment1.png |
| 1 | project1 | user1 | image1.png | attachment2.png |
This query only selects projects that are related to an image. Projects that do not have an image are not selected. I would like to select all existing projects. Also, I would like to select only one row per project. Meaning, I would like to either select only the first related image or build up multiple image-columns per project (if this is possbile - otherwise only the first image entry).
Any help is appreciated!