联接多个表一个查询

时间:2018-10-09 17:41:54

标签: mysql join

我有5个表格页面,文章,文本,图像和视频。

我的问题是如何获得

页面-(pk)pageId

文章-(pk)articleId,(fk)pageId。

SELECT pageTitle, GROUP_CONCAT(articleTitle) 
FROM pages 
JOIN articles ON articles.pageId = pages.pageId 
GROUP BY pageTitle

结果:良好

joinPagesArticlesResult 要加入:

articles(pk)articleId

文本-(fk)articleId

图片(fk)articleId

视频(fk)articleId

SELECT pageTitle, GROUP_CONCAT(articleTitle) AS articleTitle, 
group_concat(textId) AS textId, group_concat(text) AS text, 
group_concat(imageId) AS imageId,group_concat(imageLoc) AS imageLoc , 
group_concat(videoId) AS videoId,group_concat(videoLoc) AS videoLoc 
FROM articles 
JOIN pages ON pages.pageId = articles.pageId  
JOIN text ON text.articleId = articles.articleId
JOIN images ON images.articleId = articles.articleId
JOIN videos ON videos.articleId = articles.articleId
GROUP BY pageTitle

结果:GROUP_CONCAT(文章标题)的TYSON1丢失

joinTextImagesVideos

我希望能够在一张桌子上全部加入。以及让tyson1显示在查询中。不知道为什么它不显示。我不确定我是否在执行正确的连接类型,是否需要两个SELECT语句来获取此数据,或者我是否未正确执行别名。

每个表中的列如下

页面:

Page columns

文章:

Article Columns

文本:

Text Columns

图片:

Image Columns

视频:

Videos Columns

1 个答案:

答案 0 :(得分:0)

尝试使用左联接的下一个查询:

SELECT
    pageTitle,
    GROUP_CONCAT(articleTitle) AS articleTitles,
    GROUP_CONCAT(textId) AS textIds,
    GROUP_CONCAT(text) AS texts,
    GROUP_CONCAT(imageId) AS imageIds
    GROUP_CONCAT(imageLoc) AS imageLocs,
    GROUP_CONCAT(videoId) AS videoIds,
    GROUP_CONCAT(videoLoc) AS videoLocs
FROM
    articles
JOIN
    pages ON pages.pageId = articles.pageId
LEFT JOIN
    text ON text.articleId = articles.articleId
LEFT JOIN
    images ON images.articleId = articles.articleId
LEFT JOIN
    videos ON videos.articleId = articles.articleId
GROUP BY
    pageTitle