简体   繁体   中英

How can I rewrite subquery inside JOIN?

I'm not very fluent in SQL and my question is how can I rewrite the following statement to make it look more natural. The select I'm trying to write joins two tables -- "users" and "stats" -- and I know id's of users in advance. It's probably something very basic but I'm not an SQL ninja yet.

select
    u.id,
    sum(s.xxx)
from
    (
        select id from users where id in (100, 200, 300)
    ) u
    left join
    stats s
        on u.id = s.user_id
group by
    u.id
;

The part that looks strange is

    (
        select id from users where id in (100, 200, 300)
    ) u

Suggest me the right way. Thanks

That's a complicated way of saying

.... WHERE id in (100,200,300)

In your WHERE clause.

The whole thing could be rewritten as:

select
    u.id,
    sum(s.xxx)
from
    users u
left join stats s
    on s.user_id = u.id
where u.id in (100, 200, 300)
group by
    u.id

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