我有一个场景,假设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条评论,则应该返回最新的评论。谢谢
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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 |
+-----------+---------+-------------+--------+----------------+