查询数据库的结果

时间:2018-05-10 07:18:31

标签: php mysql laravel-5

我有两张桌子:画廊和共享画廊。

画廊结构:(用于存储个别学生的图像。一名学生包含多个图像)

id, student_id, classroom_id, image

shared_galleries的结构:(用于存储教室中所有学生共有的图像。一个教室包含许多图像):

id,classroom_id,image

除了这两张桌子外,我还有学生桌子和教室桌子。学生表存储了教室_id。

我需要获取一个查询,以便我可以为学生显示存储在“画廊”中的图像,以及存储在该学生所属的教室的共享库中的图像。我怎样才能做到这一点?这样的东西会返回重复的结果:

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

2 个答案:

答案 0 :(得分:0)

您需要让学生加入关系中的shared_galleries以获得正确的结果

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

这应该为您提供:student_id的学生的所有图片, 我还添加了is_shared列,以防您需要了解图片的来源

答案 1 :(得分:-1)

由于您的图像是基于每个记录存储的(在图库和共享图库中,因此不需要使用JOIN。请改用UNION:

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

这将生成一个记录列表,每个记录包含一个图像(因为每个学生的图像数量和每个教室的图像永远不一致的数字)

如果你想做一些额外的事情并确保你的教室图像总是链接到正确的学生,那么在开头声明一个变量来设置student_id值,然后在第二个SELECT语句中使用它。