我的数据库中有这两个表:
╔════════════════╗
║ beer ║
╠════════════════╣
║ id ║
║ name ║
║ ... ║
╚════════════════╝
╔════════════════╗
║ checkin ║
╠════════════════╣
║ id ║
║ beer_id ║
║ user_id ║
║ date ║
║ ... ║
╚════════════════╝
我做了这个简单的查询,它返回了啤酒登记的次数:
SELECT COUNT(c.id) as TOTAL, b.*, c.*
FROM beer b
JOIN checkin c ON c.beer_id = b.id
GROUP BY c.beer_id
ORDER BY TOTAL DESC
修改它的最佳方法是什么,以便" TOTAL"返回的计数是由唯一用户返回的(如果用户对同一啤酒进行了多次签到,则只计算一次)?
答案 0 :(得分:1)
通过对beerId进行分组来计算不同的用户。
SELECT COUNT(distinct c.user_id) as TOTAL
FROM beer b
JOIN checkin c ON c.beer_id = b.id
GROUP BY c.beer_id
ORDER BY TOTAL DESC