2

so as text is saying I need to grab user id by name from one table and then select count from another table by that ID. is it possible?


users table

ID | User

online table

ID
1
  • 1
    It would be easier to understand your requirements if you showed some sample data, the format of your expected output, what you had tried so far and what problems you are having. Sep 30, 2014 at 0:38

2 Answers 2

4

How about something more like:

SELECT COUNT(users.id)
FROM users
    INNER JOIN online
        ON online.ID = users.ID
WHERE users.id = 'myuser';
2
  • I would expect the SQL engine to optimize away the extra select into a join in the execution plan in most cases, but I agree it is usually best not to go into a sub-select when it can be done more simply.
    – Phrancis
    Sep 22, 2016 at 20:11
  • From my understanding, this solution is better than the solution with multiple selects because the dbms can do optimizations on the joins.
    – Patrick
    Sep 22, 2016 at 20:34
1

Here it is:

SELECT COUNT(*) FROM online WHERE ID = (SELECT ID FROM users WHERE name = 'myuser')

Not the answer you're looking for? Browse other questions tagged or ask your own question.