从两个不同的表中选择两个字段作为一个(使用Join)(MYSQL)

时间:2011-10-27 17:47:20

标签: mysql select join

我有以下SQL,以两种不同的方式选择文章。所有文章都存储在Articles表中。有些被标记为月份文章(Articles_Fitness),而其他被标记为纯健身文章(ArticlesInCategories)。

我的问题是我需要选择Articles_Fitness.StartDate和Articles.PublicationDate作为Formatted_Date。这可能,或者我需要将其标记为Formatted_Date1和Formatted_Date2,然后检查何时我输出了吗?

SELECT 
       Articles.ArticleID, 
       Articles.Title, 
       Articles.Author, 
       Articles.Abstract, 
       date_format(Articles_Fitness.StartDate, '%M %d, %Y') AS Formatted_Date,
       date_format(Articles.PublicationDate, '%M %d, %Y') AS Formatted_Date
     FROM 
       Articles 
       LEFT JOIN Articles_Fitness
            ON Articles_Fitness.ArticleID = Articles.ArticleID
            AND Articles_Fitness.StartDate <= CURDATE()
       LEFT JOIN ArticlesInCategories 
            ON ArticlesInCategories.ArticleID = Articles.ArticleID
            AND ArticlesInCategories.CategoryID = '1'
     WHERE 
       Articles.Body IS NOT NULL AND
       Articles.Body != '' AND
       Articles.Public ='1'

1 个答案:

答案 0 :(得分:1)

您是否想要Articles_Fitness.StartDate如果有,Articles.PublicationDate?您可以在一列中返回:

...
DATE_FORMAT(COALESCE(Articles_Fitness.StartDate, Articles.PublicationDate),
            '%M %d, %Y') AS Formatted_Date
...