连接3个表并排序

时间:2013-06-22 03:05:30

标签: mysql sql

我有三张桌子,我想放在一起。包含所有用户视频的视频表,包含所有用户图像的图像表和摄像头表。我想列出所有图片和视频并对其进行排序

带有(videoid, userid, cameraid, videosize, datetime, deleted, videolength, videoname)

前缀_视频表 带有(imageid, userid, cameraid, imagesize, datetime, deleted, imagename)

prefix_images表 带有(userid, cameraid, ...)

prefix_cameras表

以前我只有视频表,所以这个查询给了我所需要的东西:

SELECT prefix_videos.videoid, prefix_videos.videoname, prefix_videos.videosize, 
prefix_videos.videodatetime, prefix_videos.videolength, prefix_cameras.cameraname FROM 
prefix_videos INNER JOIN prefix_cameras USING (userid,cameraid) WHERE 
prefix_videos.deleted IS NULL AND prefix_videos.userid=xxx ORDER BY 
prefix_videos.datetime DESC

但是现在我正在添加一个图像表。所以我想要的是用以下内容构建一个表:

imageid/videoid, cameraid, imagesize/videosize, datetime (either from image or video table), videoname/imagename

因为我现在正在将图像和视频表结合起来给出一个结果,我不确定另一个INNER JOIN在这里有意义吗?

此处的另一个重要部分是检查已删除条目的NULL以及按日期对这些条目进行排序的能力,无论是来自图像还是视频。

2 个答案:

答案 0 :(得分:1)

您可以分别为视频和图像创建两个选择,然后将它们与联合一起使用。凌乱的部分是你必须在afaik后排序

select * from(
SELECT prefix_videos.videoid, prefix_videos.videoname, prefix_videos.videosize, 
    prefix_videos.videodatetime, prefix_videos.videolength, prefix_cameras.cameraname FROM 
    prefix_videos INNER JOIN prefix_cameras USING (userid,cameraid) WHERE 
    prefix_videos.deleted IS NULL AND prefix_videos.userid=xxx ORDER BY 
    prefix_videos.datetime DESC
    union
    SELECT prefix_images.imageid, prefix_images.imagename, prefix_images.imagesize, 
    prefix_images.imagesdatetime, prefix_images.videolength, prefix_cameras.cameraname FROM 
    prefix_images INNER JOIN prefix_cameras USING (userid,cameraid) WHERE 
    prefix_images.deleted IS NULL AND prefix_images.userid=xxx ORDER BY 
    prefix_images.datetime DESC
)a order by 'mycolumn'

select imageid/videoid, cameraid, imagesize/videosize, datetime (either from image or video table), videoname/imagename

from 
(select imageid as 'imageid/videoid', cameraid ,imagesize as 'imagesize/videosize', datetime, imagename as 'videoname/imagename' from prefix_images where ...
union 
select videoid as 'imageid/videoid', cameraid ,videosize as 'imagesize/videosize', datetime, videoname as 'videoname/imagename' from prefix_videos where ...
)as temptable
inner join whatever_your_table on temptable.selected_column=whatever_your_table .equivalent_column
order by 'mycolumn' 

答案 1 :(得分:0)

简而言之,是的,您可以在加入时加入JOIN。语法通常类似于

select [stuff] from [tableA]
 join [tableB]
 on [tableA.column] = [tableB.column]
 join [tableC]
 on [tableAorTableB.column] = [tableC.column]
 where [conditions]

等等。我过于简单了,但你明白了。