2

这是我的代码:

<?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 表连接起来,该表计算该板的点赞数。

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

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

4

2 回答 2

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 个查询几乎总是更有效。您应该尽可能地努力这样做。

于 2013-06-14T20:18:02.477 回答
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
于 2013-06-14T20:18:19.533 回答