I am working on a project management system and having to use multiple MySQL tables (messages, todo items, events, etc.) to pull and sort data from into a structured format using PHP.
The format should be similar to this
<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 &l开发者_运维知识库t;br />
Todo Item, Item name, Item Description <br />
Message, Message title <br />
</p>
Example MySQL tables are below:
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);
What would be the best way to handle this efficiently?
A union query to retrieve all the items:
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
Then a simple state machine to handle output:
$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 />";
}
精彩评论