从两个表中选择两列,并按其值DESC排序

时间:2012-12-16 11:34:45

标签: php mysql

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

          <?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 ;

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

1 个答案:

答案 0 :(得分: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