爲了得到第N(在這裏2)信息時,請
SELECT
user_id
, message_id
FROM (
SELECT
user_id
, message_id
, id
, (CASE WHEN @user_id != user_id THEN @rank := 1 ELSE @rank := @rank + 1 END) AS rank,
(CASE WHEN @user_id != user_id THEN @user_id := user_id ELSE @user_id END) AS _
FROM (SELECT * FROM MessageSent ORDER BY user_id, id) T
JOIN (SELECT @cnt := 0) c
JOIN (SELECT @user_id := 0) u
) R
WHERE rank < 3
ORDER BY user_id, id
;
它採用了RANK替代品,從@Seaux response衍生的MySQL是否有Oracle的「解析函數相當於」?
將其擴展到你原來的問題,只需添加相應的計算:
SELECT
COUNT(DISTINCT MO.user_id) * 100/
(SELECT COUNT(DISTINCT user_id)
FROM (
SELECT
user_id
, message_id
, id
, (CASE WHEN @user_id != user_id THEN @rank := 1 ELSE @rank := @rank + 1 END) AS rank,
(CASE WHEN @user_id != user_id THEN @user_id := user_id ELSE @user_id END) AS _
FROM (SELECT * FROM MessageSent ORDER BY user_id, id) T
JOIN (SELECT @cnt := 0) c
JOIN (SELECT @user_id := 0) u
) R2
WHERE rank < 3
) AS percentage_who_read_one_of_the_first_messages
FROM MessageOpened MO
JOIN
(SELECT
user_id
, message_id
FROM (
SELECT
user_id
, message_id
, id
, (CASE WHEN @user_id != user_id THEN @rank := 1 ELSE @rank := @rank + 1 END) AS rank,
(CASE WHEN @user_id != user_id THEN @user_id := user_id ELSE @user_id END) AS _
FROM (SELECT * FROM MessageSent ORDER BY user_id, id) T
JOIN (SELECT @cnt := 0) c
JOIN (SELECT @user_id := 0) u
) R
WHERE rank < 3) MR
ON MO.user_id = MR.user_id
AND MO.message_id = MR.message_id
;
隨着MySQL的無熱膨脹係數,並且在只讀數據庫中 - 我看到繞在上面的查詢沒有辦法在聲明中兩次。
看到它的行動:SQL Fiddle。
請評論如果和因爲這需要調整/進一步的細節。
爲什麼不創建一個在db中插入消息日期的日期時間列? – Santiago
@Santiago time_sent的列實際上是一個日期時間,而不僅僅是時間。編輯帖子澄清。另外,正如筆記中提到的那樣,它是一個只讀數據庫。 – Brandon
您是否要求提供* all *用戶的百分比,或者只有那些收到至少一條消息的用戶? – trincot