【问题标题】:Blog and news intertwined - Join or Union or something else?博客和新闻交织在一起 - 加入或联合或其他?
【发布时间】:2011-09-14 06:58:21
【问题描述】:

我有 4 张桌子。

news:                news_link:            blog
---------            -----------           ---------
news_id,             news_link_id,         blog_id,  
news_title,          news_link_news_id,    blog_artist_id, 
news_content,        news_link_artist_id   blog_title, 
news_image,                                blog_content,  
news_date,                                 blog_date, 
news_sticky_status,                        blog_date_edited, 
news_sticky_order,                         blog_status,       
news_status,                               blog_keywords
news_keywords, 
news_date_edited 

另一张桌子是给艺术家的

我在执行基本连接以使用 news_link 将新闻项目链接到艺术家时没有问题。

我的博客表中有artist_id。

我想在特定艺术家页面上按日期显示博客条目,并让与该艺术家相关的新闻项目出现在博客项目中。

这是我想要的输出:

title, date, content, status

我已经尝试了一些连接。我需要工会吗?这些表有不同的标签,新闻表需要 news_link 连接才有意义。

实现这一目标的最佳方法是什么?

【问题讨论】:

  • 发布更多架构 - 至少是外键。但简而言之,使用JOIN 是可行的方法。
  • 新闻 - news_id、news_title、news_content、news_image、news_date、news_sticky_status、news_sticky_order、news_status、news_keywords、news_date_edited
  • news_link - news_link_id, news_link_news_id, news_link_artist_id
  • 博客 - blog_id、blog_artist_id、blog_title、blog_content、blog_date、blog_date_edited、blog_status、blog_keywords
  • 对于这个页面,我只需要:标题、日期、内容、状态。但我需要知道它何时是与博客项目相对的新闻项目

标签: php mysql join union


【解决方案1】:

我认为需要union,如下所示:

<?php
$artist = mysql_real_escape_string($_GET['artist']);
$query = 
"SELECT is_news, title, date, content, status FROM (  
  SELECT
      1 as is_news
    , a.artist_id as id 
    , n.news_title as title
    , n.news_date as date
    , n.news_content as content
    , n.news_status as status
  FROM artist a
  INNER JOIN news_link nl ON (a.artist_id = nl.news_link_artist_id)
  INNER JOIN news n ON (n.news_id = nl.news_link_news_id)
  WHERE a.artist_id = '$artist'
UNION
  SELECT 
      0 as is_news
    , a.artist_id as id
    , b.blog_title as title
    , b.blog_date as date
    , b.blog_content as content
    , b.blog_status as status
  FROM artist a
  INNER JOIN blog b ON (a.artist_id = b.blog_artist_id)
  WHERE a.artist_id = '$artist'
) s
ORDER BY s.id, s.date";

is_news 将是 1 用于新闻项目,0 用于博客项目。

如果您选择多位艺术家,查询将对每位艺术家的结果进行排序。

【讨论】:

  • 谢谢约翰。艺术家 ID 已经作为 $artist_id 存在 - 在 $GET 中传递 - 这种加入和联合对我来说是新的,所以有点令人困惑。我会把 $artist_id 放在哪里,a 是什么。 n.湾。 s。在声明中为?再次感谢
  • a,n,s 是artistnews 等的别名。所以我不会伤到我的手指。联合将两个选择粘合在一起,还有另一个选择混合了按日期排序的unioned 结果。
  • 除非您出于某种原因不顾一切地将id 字段排除在结果集中之外,否则不需要外部选择。您可以在最后一个 UNIONed 查询之后简单地指定 ORDER BY 子句。
  • @djacobson,但这只会对最后一个联合选择进行排序,而不是第一个,我希望它们混在一起,除非你的意思是 (select... union select ...) order by id
  • 啊,这让我头疼!我以前从未使用过 Union,我发现非常混乱......我已经把它放在我的页面中并检查了命名,但我还不能让它工作。正在使用正常的 $result 和 $num 和 while 进行查询,但在 $num_rows 处失败
猜你喜欢
  • 2011-03-24
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多