[英]SQL complicated sql query
Imagine this tables: 想象一下这个表:
| USER |
|------|
| _id |
| PHOTO |
|-------|
| _id |
| user | - who uploaded it
| RATING |
|--------|
| user | - who vote
| photo | - for which foto
And then I need to extract All photos uploaded by $user And on top of that, what rating the photo has... 然后,我需要提取$ user上传的所有照片,最重要的是,该照片的评级是多少...
for example: 例如:
USER
1
PHOTO
50 | 1
51 | 1
52 | 1
RATING
2 | 50
3 | 51
2 | 51
2 | 52
4 | 51
3 | 50
My Expected result for function get_info($id): 我对函数get_info($ id)的预期结果:
$id = 1;
result:
_id | rating
50 | 2
51 | 3
52 | 1
Is there possible one task sql ? 是否有可能执行一项任务sql? thanks
谢谢
Use join and count with group by 使用连接并按分组计数
select p._id,count(distinct r.user)
from photo p
join rating r on(p._id=r.photo)
where p.user = 1
group by p._id
Since your photo table has an association with rating table as _id is related to the photo column of rating table so join them, then count each distinct user for each photo 由于您的照片表与评分表相关联,因为_id与评分表的照片列相关,因此将它们加入,然后为每张照片计算每个不同的用户
Demo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.