Answer the question
In order to leave comments, you need to log in
How to write a SQL query with a sub-select?
Hello,
There is a table tasks
id | task_name | task_created
------------------------------------------------
1 | Bring water | 15-09-2017
2 | Feed the cats | 14-09-2017
3 | Scratch dogs| 12-09-2017
4 | Borrow money | 15-09-2017
(two tasks created on the 15th)
And table uploads
id | image_path | timestamp
-----------------------------------------------------
1 | cat.jpg | 05-09-2017
2 | dogs.jpg | 15-09-2017
3 | birds.jpg | 12-09-2017
4 | star.jpg | 15-09-2017
(two uploads created on the 15th)
What I want: I want to get all the records from the tasks table, as well as the image_path from the uploads table, which has the same uploads.timestamp as task.task_created. If the task was created on 09/10/2017, and there are no records with this date in uploads, I want to get null in the column on the right table (uploads.timestamp field).
Important: for one task, you need to get one path to the picture with a condition like LIMIT 1 ORDER BY id ASC
I wrote something similar:
SELECT task_name, image_path FROM tasks left join uploads on (uploads.timestamp = tasks.task_created)
, but the results are duplicated in the selection, and I think that this should be written not through join, but with a nested select. Answer the question
In order to leave comments, you need to log in
SELECT task_name,
(SELECT image_path FROM uploads
WHERE uploads.timestamp = tasks.task_created
LIMIT 1) as im_path
FROM uploads
Your desire is due to an incorrectly designed base.
Read about the 3rd normal form of tables.
In this case, you need to:
a) task has strictly 1 or 0 pictures, pictures are only in tasks:
add the task_id field to uploads
b) otherwise:
create a new table xref_task_upload of the form (task_id, upload_id)
Your mistake is binding to timestamp which is not unique. You need to bind to a unique task id, that is, the uploads table should look like (id, image_path, task_id).
On existing data, you will either get a Cartesian product of tables, or one picture, for example dogs.jpg, will be attached to two different tasks.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question