ORDER BY变量AFTER语句

时间:2013-06-14 20:13:09

标签: php mysql sql sql-order-by

这是我的代码:

<?php 
$data = mysql_query("SELECT * FROM board") or die(mysql_error());
while($info = mysql_fetch_assoc( $data ))
{ 
if(!empty($info['user'])){
Print "".$info['user'].""; }
else {
}

myOtherQuery($info['id']);
}

function myOtherQuery($id) {

$result3 = mysql_query("SELECT COUNT(source_user_id) FROM likes 
INNER JOIN pins ON pins.id = likes.pin_id 
WHERE pins.board_id='$id'");
$c = mysql_result($result3, 0); // Cumulative tally of likes for board
{
Print "$c";
}
}
?>

第一部分获取用户姓名和董事会详细信息(董事会与相册一样)。

第二部分将该数据与另一个sql表连接起来,该表计算了主板的喜欢数量。

两者都显示为名称和由数字表示的分数。

默认情况下,它们按创建日期排序。我希望能够通过分数来订购它们。但是,由于分数是在代码的第二部分确定的,我不知道如何实现它。有可能吗?

2 个答案:

答案 0 :(得分:2)

解决方案当然是首先一次查询两个,通过LEFT JOIN对每个board_id返回计数的子查询进行查询:

SELECT
  board.*,
  /* Your PHP code will retrieve the likes count via this alias `numlikes` as in $info['numlikes'] */
  numlikes
FROM
  board
  LEFT JOIN (
    /* Subquery returns count per board_id */
    SELECT pins.board_id, COUNT(source_user_id) AS numlikes
    FROM
     likes
     INNER JOIN pins ON pins.id = likes.pin_id
    GROUP BY pins.board_id
  ) likes ON board.id = likes.board_id
ORDER BY numlikes

在循环中执行单个查询而不是 n 查询几乎总是显着更高效。你应该尽可能地努力。

答案 1 :(得分:0)

您可以在一个查询中执行此操作

SELECT board.*, count(likes.source_user_id) as score
    FROM board
    INNER JOIN pins
        ON pins.board_id = board.id
    INNER JOIN likes 
        ON pins.id = likes.pin_id
ORDER BY score