I have two tables : galleries and shared galleries.
Structure of galleries: (for storing images of individual students. One student contains multiple images)
id, student_id, classroom_id, image
Structure of shared_galleries: (for storing images which are common to all students in a classroom. One classroom contains many images):
id,classroom_id,image
Other than these two tables I have students table and classrooms table. Students table store the classroom_id.
I need to get a query so that I can display the images stored in 'galleries' for a student and those stored in shared gallery of the classroom in which that student belongs in a single page. How can I achieve this ? Something like this returns duplicated results :
select galleries.id as gid,
shared_galleries.id as sid,
galleries.student_id, galleries.classroom_id
from galleries
inner join shared_galleries on galleries.classroom_id=shared_galleries.classroom_id
where galleries.student_id=31 and galleries.classroom_id=28
You will need to join the student to the shared_galleries
along the relations to get the right results
SELECT
g.image AS image,
0 AS is_shared
WHERE
g.student_id = :student_id
FROM
galleries AS g
UNION
SELECT
sg.image AS image,
1 AS is_shared
FROM
shared_galleries AS sg
LEFT JOIN classrooms AS c ON c.id = sg.classroom_id
LEFT JOIN students AS s ON s.classroom_id = c.id
WHERE
s.id = :student_id
This should give you all the images for a student with :student_id
, I've also added the is_shared
column in case you need to know the origin of the image
Since your images are stored on a per-record basis (in both galleries and shared galleries, using a JOIN is not needed. Use a UNION instead:
SELECT
galleries.id AS ID,
galleries.student_ID AS StudentID,
galleries.classroom_id as ClassroomID,
galleries.image as Image
WHERE
galleries.student_id = 31
UNION
SELECT
shared_galleries.id AS ID,
NULL AS StudentID,
shared_galleries.classroom_id as ClassroomID,
shared_galleries.image as Image
WHERE
shared_galleries.classroom_ID = 31
This will produce a list of records, with each record containing one image (since the number of images per student and the number if images per classroom is never consistent)
If you want do a little extra and ensure that your classroom images are always linked to the correct student, then declare a variable at the beginning to set the student_id value, and then use it in the second SELECT statement.
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.