0

使用此代码,我从数据库中获取新闻并按“视图”列对其进行排序:

          <?php
          $getnewsinfo = mysql_query("SELECT * FROM news ORDER BY views DESC LIMIT 5");
    while($newsinforow = mysql_fetch_array($getnewsinfo))
    {
    $newsid = $newsinforow['id'];
    $title = $newsinforow['title'];
    $author = $newsinforow['author'];
    $date = date('d.m.Y', $newsinforow['date']);
    $picture = $newsinforow['picture'];
    $picture_desc = $newsinforow['picture_desc'];
    $category = $newsinforow['category'];
    $text = $newsinforow['text'];
?>

现在我想按浏览量和评论数排序新闻,但我不知道如何。这是我的数据库结构:

CREATE TABLE IF NOT EXISTS `news` (
  `id` int(11) NOT NULL auto_increment,
  `views` int(11) NOT NULL default '0',
  `title` varchar(255) NOT NULL,
  `author` varchar(255) NOT NULL,
  `date` varchar(255) NOT NULL,
  `picture` varchar(255) NOT NULL,
  `picture_desc` varchar(255) NOT NULL,
  `category` varchar(255) NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;

CREATE TABLE IF NOT EXISTS `news_comments` (
  `id` int(11) NOT NULL auto_increment,
  `news_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `website` varchar(255) NOT NULL,
  `text` text NOT NULL,
  `date` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=16 ;

我也想问你……你对代码和数据库结构有什么意见吗?

4

1 回答 1

0

试试这个 sql

SELECT n.*,count(nc.id) as cnt FROM news as n, news_comments as nc where n.id = nc.news_id group by nc.news_id ORDER BY views DESC,cnt DESC LIMIT 5
于 2012-12-16T11:39:21.347 回答