繁体   English   中英

如何在按日期显示的标题下按日期排序的多个表中显示排序的数据?

[英]How can I display sorted data from multiple tables ordered by date under dated headings?

我正在一个项目管理系统上工作,不得不使用多个MySQL表(消息,待办事项,事件等)来使用PHP将数据提取和分类为结构化格式。

格式应与此类似

<p><b>Today</b></p>
<p>
  Todo Item, Item name, Item Description <br />
  Todo Item, Item name, Item Description <br />
  Message,   Message title               <br />
  Todo Item, Item name, Item Description <br />
  Todo Item, Item name, Item Description <br />
  Message,   Message title               <br />
</p>
<p><b>June 22, 2011</b></p>
<p>
  Todo Item, Item name, Item Description <br />
  Todo Item, Item name, Item Description <br />
  Todo Item, Item name, Item Description <br />
  Message,   Message title               <br />
  Todo Item, Item name, Item Description <br />
  Message,   Message title               <br />
</p>

示例MySQL表如下:

CREATE TABLE `todo` (
  `id` int(12) NOT NULL auto_increment,
  `item` varchar(255) NOT NULL default '',
  `description` text NOT NULL,
  `created` int(12) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM;

INSERT INTO `todo` (`id`, `item`, `description`, `created`) VALUES
(1, 'test to-do list 1', 'this is simply a test 1', 1308847222),
(2, 'test to-do list 2', 'this is simply a test 2', 1308847318),
(3, 'test to-do list 3', 'this is simply a test 3', 1308847371),
(4, 'test to-do list 4', 'this is simply a test 4', 1306847441),
(5, 'test to-do list 5', 'this is simply a test 5', 1306848208);

CREATE TABLE `messages` (
  `id` int(12) NOT NULL auto_increment,
  `title` varchar(255) NOT NULL default '',
  `message` text NOT NULL,
  `created` int(12) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM;

INSERT INTO `messages` (`id`, `title`, `message`, `created`) VALUES
(1, 'test messages 1', 'this is simply a test 1', 1308847222),
(2, 'test messages 2', 'this is simply a test 2', 1308847318),
(3, 'test messages 3', 'this is simply a test 3', 1308847371),
(4, 'test messages 4', 'this is simply a test 4', 1306847441),
(5, 'test messages 5', 'this is simply a test 5', 1306848208);

有效处理此问题的最佳方法是什么?

联合查询以检索所有项目:

SELECT DATE(created) AS d, item, description, 'todo' AS src
FROM todo

UNION

SELECT DATE(created) AS d, title, message, 'messages' AS src
FROM messages

ORDER BY created

然后是一个简单的状态机来处理输出:

$prev_date = null;
$first = true;
while($row = mysql_fetch_assoc($query_results)) {
   if ($prev_date <> $row['d') {
        if (!$first) {
            echo "</p>';
        }
        echo "<p><b>{$row['d']</b></p><p>";
   }
   echo " ... rows stuff<br />";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM