我希望我能让自己理解得足够多!我有以下SQL查询
SELECT DATE_FORMAT(calendar_date,'%W %D, %M, %Y') AS calendar_date,calendar_entry_title,calendar_entry_teaser
FROM calendar_month
LEFT JOIN calendar_entry ON calendar_entry.calendar_id = calendar_month.calendar_id
ORDER BY calendar_date
以下是我正在处理的表格细节。
CREATE TABLE IF NOT EXISTS `calendar_entry` (
`calendar_entry_id` int(11) NOT NULL AUTO_INCREMENT,
`calendar_id` int(11) NOT NULL,
`school_id` int(11) NOT NULL,
`calendar_entry_title` varchar(250) NOT NULL,
`calendar_entry_teaser` varchar(250) NOT NULL,
`calendar_entry_text` text NOT NULL,
PRIMARY KEY (`calendar_entry_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `calendar_entry`
--
INSERT INTO `calendar_entry` (`calendar_entry_id`, `calendar_id`, `school_id`, `calendar_entry_title`, `calendar_entry_teaser`, `calendar_entry_text`) VALUES
(1, 1, 1, 'School Event 1', 'School event information 1', 'This would be the full body of the text that would show on the full page for this given entry'),
(2, 1, 1, 'School Event 2', 'School event information 2', 'This would be the full body of the text that would show on the full page for this given entry');
CREATE TABLE IF NOT EXISTS `calendar_month` (
`calendar_id` int(11) NOT NULL AUTO_INCREMENT,
`school_id` int(11) NOT NULL,
`calendar_date` date NOT NULL,
PRIMARY KEY (`calendar_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `calendar_month`
--
INSERT INTO `calendar_month` (`calendar_id`, `school_id`, `calendar_date`) VALUES
(1, 1, '2012-08-11'),
(2, 1, '2012-08-12');
我遇到的问题是,calendar_month表中只有2行。其中一行在month_entry表中有2行与之相关。当我运行我所拥有的查询时,它将显示3行。我需要做的只是显示2行,有两行的月份我需要显示为一行。这可以通过我如何设置来完成吗?
由于
结果 -
Saturday 11th, August, 2012 School Event 1 School event information 1
Saturday 11th, August, 2012 School Event 2 School event information 2
Sunday 12th, August, 2012 NULL NULL
我真正想要的是什么 -
Saturday 11th, August, 2012 School Event 1 School event information 1 School Event 2 School event information 2
Sunday 12th, August, 2012 NULL NULL
答案 0 :(得分:0)
你不能仅在mysql中获得那种结果,或者每行使用2个子查询,这迟早会使你的服务器崩溃。相反,使用php来排序结果并存储在你的calendar_entry_title中。 例如:
$query =" SELECT DATE_FORMAT(calendar_date,'%W %D, %M, %Y') AS calendar_date,
calendar_entry_title,
calendar_entry_teaser
FROM calendar_month
LEFT JOIN calendar_entry ON calendar_entry.calendar_id = calendar_month.calendar_id
ORDER BY calendar_date, calendar_entry_title";
$result = mysql_query($query);
$events = array();
foreach($result as $r){
$events[$r['calendar_date']][] = $r;
}
echo '<pre>';
print_r($events);
echo '</pre>';
答案 1 :(得分:0)
SELECT DATE_FORMAT(calendar_date,'%W %D, %M, %Y') AS calendar_date, TMP.var1
FROM calendar_month
LEFT JOIN
(SELECT GROUP_CONCAT(calendar_entry_title, ' ',calendar_entry_teaser) AS var1, calendar_id
FROM calendar_entry
GROUP BY calendar_id) AS TMP ON TMP.calendar_id = calendar_month.calendar_id
ORDER BY calendar_date