简体   繁体   中英

sql subquery, passing a variable

Can you pass variables into subqueries, like so?

SELECT users.id AS id, 
(SELECT SUM(total) FROM (image_totals) WHERE `cat_id` IN ('5', '3') AND `user_id` =id) AS image_count

This is only part of a larger query, all being generated through Active Record, but the key issue remains, the 'id' variable, how can I pass this into my subquery? Am I looking at this all wrong?

Thanks in advance. And let me know if you need more info.

If I understood your question correctly, then yes you can.

If the tables don't contain the same columns then you don't need the table name for each column. I prefer to include the table name as it makes it easier to understand.

SELECT  users.id AS id ,
        (SELECT SUM(image_totals.total)
         FROM   image_totals
         WHERE  image_totals.cat_id IN ( '5', '3' ) AND 
                image_totals.user_id = users.id) AS image_count
FROM users

you can also use alias' for tables to make it a bit easier to type. u = user and i = image_totals.

SELECT  u.id AS id ,
        (SELECT SUM(i.total)
         FROM   image_totals AS i
         WHERE  i.cat_id IN ( '5', '3' ) AND 
                i.user_id = u.id) AS image_count
FROM users AS u

nope, that is impossible, it will have to be implemented differently.

Select has to be selecting from one consistent dataset.

Your dataset may contain complex queries.

Use GROUP BY. You want SUM(total) for each user.id for particular values of cat_id. I don't know what the rest of your query looks like, but for what was shown, you can just:

SELECT
        users.id AS id,
        SUM(total)
FROM image_totals
WHERE cat_id IN ('5', '3')
GROUP BY users.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