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

发布于 2024-12-12 09:55:12 字数 1038 浏览 1 评论 0原文

我有以下 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'

I've got the following SQL, selecting articles in two different ways. All articles are stored in the Articles table. Some are marked as Article Of The Month (Articles_Fitness), while others are marked as purely fitness articles (ArticlesInCategories).

My problem is that I need to select both Articles_Fitness.StartDate and Articles.PublicationDate as the Formatted_Date. Is this possible, or will I need to label one as Formatted_Date1 and Formatted_Date2, and then check when I output it?

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'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

漆黑的白昼 2024-12-19 09:55:12

您是说您想要 Articles_Fitness.StartDate(如果存在),否则需要 Articles.PublicationDate?您可以将其返回在一列中:

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

Are you saying you want Articles_Fitness.StartDate if present, otherwise Articles.PublicationDate? You can return that in one column:

...
DATE_FORMAT(COALESCE(Articles_Fitness.StartDate, Articles.PublicationDate),
            '%M %d, %Y') AS Formatted_Date
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文