1

我有一个场景,假设 3 个用户评论了一个 id 为 10 的业务,我如何获取评论该业务的用户的所有唯一 ID,并使用该唯一 ID 找到另一个不等于 10 的业务评论?

示例表 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 条评论,则应返回最新的一条。谢谢

4

3 回答 3

2

Try this query:

Here is link to sqlfidle with running results 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
于 2012-10-30T09:04:41.400 回答
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
于 2012-10-30T09:02:23.990 回答
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 |
+-----------+---------+-------------+--------+----------------+
于 2012-10-30T09:34:53.400 回答