来自两个表的MySQL,其中一个是左连接

时间:2017-09-05 06:46:53

标签: mysql join

我有两张几乎相同列的表 - 视频列表和画廊列表。我想继续将此连接到成员表,以便我可以从成员ID中获取成员名称。我最终得到的是按日期列排序的视频和画廊列表。我知道如何单独进行,但无法将其结合起来。以下是单独的查询:

//Video Query
SELECT videos.vid, videos.mid, videos.source, videos.category, videos.title, videos.description, videos.date_added, videos.status, members.name FROM videos LEFT JOIN members ON videos.mid=members.mid WHERE videos.status = 'published' ORDER BY date_added

//Gallery Query    
SELECT galleries.vid, galleries.mid, galleries.directory, galleries.category, galleries.title, galleries.description, galleries.date_added, galleries.status, members.name FROM videos LEFT JOIN members ON videos.mid=members.mid WHERE galleries.status = 'published' ORDER BY date_added 

但是我无法使用两个表来使用左连接。两个表使用相同的列进行左连接,使用相同的列进行排序。我可以做一个查询,还是我必须同时查询并进行某种合并?

最终结果如下:

- Video A by John
- Gallery A by John
- Video B by John
- Video C by Mary

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以将查询结合起来并编写类似

的内容
SELECT 
  videos.vid,
  videos.mid,
  videos.source,
  videos.category,
  videos.title,
  videos.description,
  videos.date_added,
  videos.status,
  galleries.vid,
  galleries.mid,
  galleries.directory,
  galleries.category,
  galleries.title,
  galleries.description,
  galleries.date_added,
  galleries.status,
  members.name 
FROM
  videos 
  LEFT JOIN members 
    ON videos.mid = members.mid members.name 
FROM
  videos 
  LEFT JOIN members 
    ON videos.mid = members.mid 
    AND videos.status = 'published' 
  LEFT JOIN galleries 
    ON galleries.mid = members.mid 
AND galleries.status = 'published' 
ORDER BY galleries.date_added,videos.date_added 

我希望这会有所帮助。