2012-10-30 82 views
1

我有一個場景,可以說3個用戶查看ID爲10的業務,我如何獲得查看該業務的用戶的所有唯一ID,並使用該唯一ID查找另一個不等於10的商業評論?mysql根據當前項目選擇相關項目

示例表user_review:

review_id | user_id | business_id | rating | review_date 
    1   2   10   3  20121030124001 
    2   2   9   3  20121022120627 
    3   2   10   4  20121023120627 
    4   3   10   4  20121024120627 
    5   3   6   3  20121022140627 
    6   4   10   2  20121025120627 
    7   4   10   5  20121030120627 
    8   3   10   2  20121010120627 
    9   4   8   5  20121028120627 

我應該得到的這些

review_id | user_id | business_id | rating | review_date 
    2   2   9   3  20121022120627 
    5   3   6   3  20121022140627 
    9   4   8   5  20121028120627 

導致上述結果,如果有一個相同的USER_ID和相同business_id最新的一個應該是回報2條評論.Thanks

+0

如果只用'business_id' = 10,是否應該顯示爲'user_id' = 5? – Devart

+0

@Devart我的朋友,user_review表是記錄當用戶提供審查 爲business_id 10,這意味着在篩選user_review表後,如果該用戶沒有任何其他評論,那麼不需要顯示任何東西 – d3bug3r

回答

2

嘗試此查詢:

這裏是鏈接到與運行結果sqlfidle http://sqlfiddle.com/#!2/cd4ea/1

SELECT 
    tblreview.*,tblusers.user_name 
FROM 
    (
     SELECT 
      MAX(tblreview.review_id) review_id 
      , tblreview.user_id 
     FROM 
      (
      SELECT 
       DISTINCT user_id 
      FROM 
       tblreview 
      WHERE business_id = 10 
     ) reviewsb10 
     INNER JOIN 
      tblreview 
     ON 
      tblreview.user_id = reviewsb10.user_id 
     AND 
      tblreview.business_id <> 10 
     GROUP BY 
      user_id 
) tblLastReviewPerUser 
INNER JOIN 
    tblreview 
ON 
    tblreview.review_id = tblLastReviewPerUser.review_id 
INNER JOIN 
    tblusers 
ON 
    tblusers.user_id = tblLastReviewPerUser.user_id 
+0

沒有結果是您的查詢返回 – d3bug3r

+0

我添加了鏈接到sqlfiddle與返回所需的結果http://sqlfiddle.com/#!2/549b0/2 – Farfarak

+0

條件怎麼樣?在上述結果中,如果對同一個user_id和同一business_id有2條評論,最新的應該是return – d3bug3r

0
SELECT t1.* 
FROM TableName t1 
INNER JOIN 
(
    SELECT user_id, business_id, MAX(review_date) review_date 
    FROM TableName 
    WHERE business_id <> 10 
    GROUP BY user_id, business_id 
) t2 ON t1.user_id = t2.user_id 
    AND t1.review_date = t2.review_date 
    AND t1.business_id = t2.business_id 
+0

不工作..# 1064 - 你的SQL語法錯誤;檢查對應於您的MySQL服務器版本的手冊,以在'WHERE business_id <> 10「附近使用正確的語法)t2 ON t1.user_id = t2.user_id AND t1.review_date = t2。'在第8行 – d3bug3r

+0

同樣的錯誤..嘗試在SQLFiddle – d3bug3r

+0

@zlippr對不起,這是一個sytax錯誤。 'WHERE'子句應該在'GROUP BY'子句之前。看我的編輯。 –

0

嘗試此查詢 -

SELECT * FROM (
    SELECT * FROM user_review 
    ORDER BY IF(business_id = 10, 1, 0), review_date DESC 
) t 
GROUP BY user_id 
HAVING 
    COUNT(IF(business_id = 10, 1, NULL)) > 0 
    AND COUNT(IF(business_id <> 10, 1, NULL)) > 0 

+-----------+---------+-------------+--------+----------------+ 
| review_id | user_id | business_id | rating | review_date | 
+-----------+---------+-------------+--------+----------------+ 
|   2 |  2 |   9 |  3 | 20121022120627 | 
|   5 |  3 |   6 |  3 | 20121022140627 | 
|   9 |  4 |   8 |  5 | 20121028120627 | 
+-----------+---------+-------------+--------+----------------+