简体   繁体   中英

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...

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):

$id = 1;

result:
_id   |  rating
50    |    2
51    |    3
52    |    1

Is there possible one task 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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM