2015-01-05 9 views
1

我工作的一個網絡/社交網站,我試圖創建一個函數來返回在你訪問它的那一刻訪問同一頁面的用戶計數。複雜的PHP MySQL查詢從不同的表

怎麼能夠通過計算和分組從表中「讀」 USER_ID從表中選擇「USERS」的用戶?

數據庫結構如下:

USERS

  • USER_ID
  • 用戶名
  • ...

READING

  • ID
  • USER_ID
  • update_timestamp
  • ...

什麼應該返回是這樣

user 
    - user_id 
    - user_name 
    - user_first_name 
    - ... 
user 
    - user_id 
    - ... 

這是一個數組,我有這樣的查詢遠

SELECT r.user_id,U。* FROM讀取R,用戶U基團BY r.user_id AS計數WHERE u.user_id = r.user_id ORDER BY計數DESC

實施例表

USERS

// user_id // user_name // user_email 
------------------------------------- 
    123 / mentos /[email protected] 
------------------------------------- 
    321 /freshmaker/[email protected] 
------------------------------------- 
    231 /hubba /[email protected] 

讀取OUTP什麼的

// id // user_id // timestamp 
-------------------------------------- 
     1 / 123 / 201501050420 
     2 / 321 / 201501050420 

實施例ut應該是

-ARRAY 
    -user 
    - 123 
    - mentos 
    - [email protected] 
    -user 
    - 321 
    - freshmaker 
    - [email protected] 
+0

幾個問題:你提到「計數和分組」,但您的樣品輸出不包括任何種類的,比如'COUNT聚集的()'。你是什​​麼意思?你如何確定「同時」標準?你有'reading.update_timestamp' - 應該有一些門檻,說'update_timestamp'已經在過去的60秒內的值? –

+0

忘記將它放在示例中,reading.update_timestamp將每隔5分鐘更新一次,例如如果您在頁面A上並且我在頁面A上,則必須看到您與我在同一頁面上。我希望這解釋得更好一點。 –

+0

請從這兩張表中發佈一小段行數 - 足以說明一組用戶同時在閱讀,而另一組則不在同一時間閱讀。鑑於這些數據,請發佈一個查詢輸出結果的表格。小組/人數還沒有很好解釋。 –

回答

0

你在找這樣的嗎?

SELECT u.* 
    FROM 
(
    SELECT DISTINCT user_id 
    FROM reading 
    WHERE update_timestamp >= NOW() - INTERVAL 5 MINUTE -- or any other appropriate time interval 
    AND user_id <> 4 -- depending on the logic you might want to exclude the current user itself 
) q JOIN users u 
    ON q.user_id = u.user_id 

這裏是一個SQLFiddle演示