3

我目前有一个查询,我从不同的表中选择 * != $this->player_id-> 这很好用。

如下所示:

$sql = "
    SELECT pi . * , p . *
    FROM player_img pi, player p
    WHERE pi.player_img_category_id = $this->category_id
    AND pi.player_img_player_id = p.player_id
    AND pi.player_img_player_id != $this->player_id";

我现在想做的有点不同:

  • 选择随机结果并按限制 10 排序
  • 在随机结果之间需要有一个特定的行- 此行应基于$this->player_id

为了得到随机结果,我想我可以这样做:

ORDER BY RAND() LIMIT 10

- 但是我如何确保包含我的特定行:

pi.player_img_player_id == $this->player_id- 这个我不知道。有什么建议么?

编辑: Allinone 的回答做了我想做的事情 - 作为奖励问题,我想知道是否可以通过 ASC p.player_firstname 以他的示例对查询结果进行排序?

4

2 回答 2

1

您可以为此使用 FIND_IN_SET() 或 FIELD() 函数。您的 order by 子句如下所示:

ORDER BY FIND_IN_SET(pi.player_img_player_id, '$this->player_id') desc, rand()

查看更多:mysql order by a fixed list

于 2013-09-03T19:23:52.267 回答
1

如何使用UNION两个查询但条件不同

SELECT q.* FROM (
    SELECT pi . * , p . *
    FROM player_img pi, player p
    WHERE pi.player_img_category_id = $this->category_id
    AND pi.player_img_player_id = p.player_id
    AND pi.player_img_player_id != $this->player_id
    UNION ALL
    SELECT pi . * , p . *
    FROM player_img pi, player p
    WHERE pi.player_img_category_id = $this->category_id
    AND pi.player_img_player_id = p.player_id
    AND pi.player_img_player_id = $this->player_id 
) q ORDER BY RAND() LIMIT 10
于 2013-09-03T19:20:12.387 回答