来自数据库的查询结果

g6ll5ycj  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(271)

我有两张table:画廊和共享画廊。
画廊的结构:(用于储存个别学生的图像。一个学生包含多个图像)

id, student_id, classroom_id, image

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

id,classroom_id,image

除了这两张table,我还有学生桌和教室桌。学生表存储教室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
zdwk9cvp

zdwk9cvp1#

由于您的图像存储在每个记录的基础上(在库和共享库中),因此不需要使用连接。改用联合体:

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\u id值,然后在第二个select语句中使用它。

3lxsmp7m

3lxsmp7m2#

你需要和这个学生一起参加考试 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 列,以防您需要知道图像的来源

相关问题