通过循环查询值排序mysql结果

时间:2011-01-29 13:49:40

标签: php mysql

我正在做以下

$def = $_GET['def']; if (!$def == 0) {$offset = 'OFFSET '.$def.'';}
$data1 = mysql_query(
   "SELECT *, DATE(post_modified) as nicedate 
     FROM (`wp_postmeta`) 
     LEFT JOIN (`wp_posts`) ON wp_postmeta.post_id = wp_posts.ID 
     LEFT JOIN (`wp_top_ten`) ON wp_posts.ID = wp_top_ten.postnumber 
     WHERE meta_value='the_value' 
     ORDER BY nicedate DESC LIMIT 16 ".$offset.""
                   ) or die(mysql_error()); 
   while($info = mysql_fetch_array( $data1 ))

 { 
   $id = $info['ID']; 
   echo "some stuff";
   $data2 = mysql_query("
                 SELECT SUM(vote) as total_vote, COUNT(*) as total_count 
                 FROM (`wp_gdsr_votes_log`) 
                 WHERE id='".$id."' AND vote_type='article'
                    ")  or die(mysql_error()); 
        while($info = mysql_fetch_array( $data2 ))
     {$vote = number_format(
            ($info['total_vote']/$info['total_count'])
                        , 2, '.', ' ');} 
             echo $vote."/5"; echo "some more stuff"; 
 } 

我如何在$data1中订购结果,其中'nicedate'将是$vote值?

2 个答案:

答案 0 :(得分:1)

您可以创建在每轮循环后填充的数组。类似的东西(在你获取$ data1的结果之后):

在$ data1之前定义一个空数组。

$newarray = array();

比,在第二个循环中:

$nicedate = info['nicedate'];

$newarray[$nicedate] = $vote;

你最终得到array('date'=>'vote', 'date2' => 'vote2',..),你可以随意排序。

答案 1 :(得分:1)

这是一个猜测,因为我无法测试它,因为我没有你的数据。但是,根据理论,您应该能够组合查询并按此方式排序。

SELECT *, DATE(post_modified) as nicedate, 
  SUM(vlog.vote) as total_vote, COUNT(vlog.*) as total_count
  (total_vote/total_count) as vote
  FROM wp_postmeta AS meta
  LEFT JOIN wp_posts AS posts  ON meta.post_id = posts.ID 
  LEFT JOIN wp_top_ten AS tten ON posts.ID = tten.postnumber 
  LEFT JOIN wp_gdsr_votes_log AS vlog ON posts.ID = vlog.id
  WHERE meta_value='the_value' 
    AND vlog.vote_type='article'
  GROUP BY vlog.id 
  ORDER BY vote DESC, nicedate DESC 
  LIMIT 16 $offset

希望我足够接近你想要的东西,至少几乎可以工作。 我现在为那里的任何愚蠢错误道歉。

如果您认为合适,请随意编辑。只需记下你改变了什么。


<强>编辑:
1. Gutterball - 添加了编辑注释。