【发布时间】:2014-01-11 18:09:51
【问题描述】:
我正在尝试显示来自两个表的项目的新闻提要。
Table 1: News - Id / Title / Date
Table 2: Shared_News - Id / News_Id / Date
来自Shared_News 的News_Id 实际上是来自News 表的Id。现在的场景...
我的新闻提要必须显示新闻表中的项目以及 Shared_News 项目。 Shared_News 项目将根据共享日期与 News 项目合并。
让我们举个例子,我们从News 表中显示 Id 的 2、4、6、8,按日期排序,如下所示
8
6
4
2
现在让支持某人在文章 8 发布后的某个日期与用户分享了 News 项目 5,它被输入到 Shared_News 表中。我希望显示以下顺序
5
8
6
4
2
现在如果在第 4 项发布后共享第 1 项,则顺序应如下所示
5
8
6
1
4
2
有人可以帮助我,因为我正在做的左连接不起作用。下面是我的代码/我正在使用 Codeigniter 框架。
$stories_finalized 下面是新闻 ID 和共享新闻 ID 的合并列表。
$select = array(
'users.name',
'story.id as story_id',
'story.date',
'story.title',
'story.user_id',
'share.date as shared_story_date'
);
$where = array('story.show' => 1);
$this->db
->select($select)
->where_in('story.id', $stories_finalized)
->join('users', 'users.id = story.user_id')
->join('share', 'share.story_id = story.id', 'LEFT')
->where($where)
->order_by('share.date, story.date', 'DESC')
->limit(STORY_QUERY_LIMIT, $from);
Story Table 中存储的数据如下所示
59 | This is an example story | 2013-09-20
45 | This is the title of the shared story | 2013-08-12
Share 表中存储的数据如下
1 | 45 | 2013-12-24
最后,我希望数据如下所示
45 | This is the title of the shared story | 2013-08-12
59 | This is an example story | 2013-09-20
提前非常感谢!
【问题讨论】:
-
我们可以有一些实际数据而不仅仅是 ids 吗?两张桌子?
-
@PeterRing 是的,我们绝对可以获取数据。
-
我删除了 SQL Server 标签,因为这是关于 MySQL 的,并添加了 codeigniter,因为它是关于 Code Igniter。
-
@foxybagga,PeterRing 的意思是,你能向我们展示数据吗?我们不知道它是如何存储的。
-
shared_story_date中存储的日期是否为空?
标签: php mysql sql codeigniter join