2012-01-14 51 views
3

今天我需要你的幫助來得到一個特定的sql select查詢。具體的mysql選擇查詢

我有下表:

table with all results

和關於特定的ID(在這種情況下ID 1)我想有這樣的結果的特定的查詢後:

USER_ID(別名對於id_sender/id_recipient),日期(也許是最大的功能,因爲我想擁有最新的日期組),郵件(計數功能的消息):

10 | 2012-01-14 09:10:05 | 4 
11 | 2012-01-13 13:52:49 | 1 
13 | 2012-01-13 20:01:17 | 1 
14 | 2012-01-14 09:20:17 | 1 

我tryed很多,但沒有得到確切的結果 - 所以我的做法是這樣的:

SELECT `id_recipient`, `id_sender`, MAX(`date`) AS `date`, COUNT(*) AS `messages` FROM `table` WHERE `id_recipient` = 1 OR `id_sender` = 1 GROUP BY `id_recipient`, `id_sender` 

但後來我得到這樣的結果:

my approach

它不是那麼糟糕,但作爲你可以看到第四行應該包含在第一行的結果中。 我希望你能找到我。隨時詢問,如果不清楚。

在此先感謝, 問候

回答

7

好了,因爲我們知道id_recipient值,我們可以用一些數學誘騙到SQL完成這個令人討厭的查詢。

設n是感興趣的人的id值。

我們知道id_recipient和id_sender的配對總是包含id值爲n的用戶。基於where子句。

因此,id_recipient + id_sender == n + id_otherPerson爲true。

生成的查詢與此非常相似。 (它已經有一段時間,但我不認爲我有什麼語法問題)

SELECT (`id_recipient` + `id_sender` - n) AS `id_otherPerson`, 
     MAX(`date`) AS `date`, COUNT(*) AS `messages` 
FROM `table` 
WHERE `id_recipient` = n XOR `id_sender` = n 
GROUP BY `id_otherPerson`; 

編輯:我把它改成一個XOR,因此,如果人n條消息的人N,也不會造成所有的值都會增加n的消息次數。

+0

1 + 10 - 1 = 10和10 + 1 - 1 = 10 – JustinDanielson 2012-01-14 09:31:15

+0

該死的,從來沒有想過這樣的 - 這真是一個很好的處理這樣一個問題的方式 - 我會記住這個同樣的問題! – user1104419 2012-01-14 09:32:30

+0

它完成了工作嗎? – JustinDanielson 2012-01-14 09:34:16

0

這個怎麼樣?

SELECT user_id, MAX(date), COUNT(*) 
FROM (
    SELECT id_recipient AS 'user_id', date 
    FROM table 
    WHERE id_recipient <> 1 AND id_sender = 1 
    UNION 
    SELECT id_sender AS 'user_id', date 
    FROM table 
    WHERE id_recipient = 1 AND id_sender <> 1 
) AS tbl 
GROUP BY user_id 

它假定您要使用id_recipient如果id_sender爲1,如果id_sender是id_recipient 1

0

我相信你想應該是如下

10 | 2012-01-13 20:01:17 | 3 
11 | 2012-01-13 13:52:49 | 1 
13 | 2012-01-13 20:01:17 | 1 

我說因爲你是混合id_recipient和輸出id_sender

+1

他想將1到10之間的任何通信分組。不管1是發送者還是接收者。 14應該包括在內,因爲14收到來自1. – JustinDanielson 2012-01-14 09:30:25

+0

的消息好吧...讓我檢查... – 2012-01-14 09:30:55

+0

justinDanielson是對的 - 我想收集兩個用戶之間的所有消息,不僅僅是發送或接收的消息。 – user1104419 2012-01-14 09:33:46