我有一種在我的網站的Facebook式的喜歡/不喜歡系統和現在用的是下面的查詢搶到喜歡的特定崗位+好惡:如何形成2種不同的順序MySQL查詢BY語句
SELECT DISTINCT * FROM posts WHERE cid='$cid' AND pid=".implode(" OR pid=",$pids)." ORDER BY time DESC
$pid
是要搜索的post ID的數組。
zbid
是當前正在訪問該頁面的用戶的ID。現在,如果該用戶評價(喜歡/不喜歡)該帖子,他的結果應該首先返回,然後在那之後通過time DESC
訂購結果。
我該如何去修改查詢來做到這一點?
如果posts
表具有以下數據:
+----+-----+------+-----+--------+------+ | id | cid | zbid | pid | rating | time | +----+-----+------+-----+--------+------+ | 1 | 1 | 1 | 1 | 1 | 1 | +----+-----+------+-----+--------+------+ | 2 | 1 | 2 | 1 | -1 | 4 | +----+-----+------+-----+--------+------+ | 3 | 1 | 3 | 2 | 1 | 2 | +----+-----+------+-----+--------+------+ | 4 | 2 | 4 | 1 | -1 | 3 | +----+-----+------+-----+--------+------+ | 5 | 1 | 5 | 1 | 1 | 8 | +----+-----+------+-----+--------+------+ | 6 | 1 | 6 | 1 | -1 | 7 | +----+-----+------+-----+--------+------+
目前的select語句(上圖)將返回以下信息(與$pid = array(1);
):
+----+-----+------+-----+--------+------+ | id | cid | zbid | pid | rating | time | +----+-----+------+-----+--------+------+ | 5 | 1 | 5 | 1 | 1 | 8 | +----+-----+------+-----+--------+------+ | 6 | 1 | 6 | 1 | -1 | 7 | +----+-----+------+-----+--------+------+ | 2 | 1 | 2 | 1 | -1 | 4 | +----+-----+------+-----+--------+------+ | 4 | 2 | 4 | 1 | -1 | 3 | +----+-----+------+-----+--------+------+ | 1 | 1 | 1 | 1 | 1 | 1 | +----+-----+------+-----+--------+------+
但是,如果人用zbid=4
正在訪問該頁面,它應該將該結果(如果存在)提升至頂端,如下所示:
+----+-----+------+-----+--------+------+ | id | cid | zbid | pid | rating | time | +----+-----+------+-----+--------+------+ | 4 | 2 | 4 | 1 | -1 | 3 | +----+-----+------+-----+--------+------+ | 5 | 1 | 5 | 1 | 1 | 8 | +----+-----+------+-----+--------+------+ | 6 | 1 | 6 | 1 | -1 | 7 | +----+-----+------+-----+--------+------+ | 2 | 1 | 2 | 1 | -1 | 4 | +----+-----+------+-----+--------+------+ | 1 | 1 | 1 | 1 | 1 | 1 | +----+-----+------+-----+--------+------+
變量$zbid
設置爲正在訪問該頁面的用戶的zbid
。
請再次編輯你的問題,並添加一些sammple數據和數據的查詢後所需要的輸出,所以這是一個更清楚你想要做什麼。謝謝。 :-) – 2012-08-08 17:28:56