0

I am looking for help in writing a MYSQL query. I have two tables, one called users and another called switched. The users table has the following structure:

uid
first_name
last_name

And the switched table:

uid (references user table)
switch_number
reg_date

The switched table has multiple uid values and I wish to generate a table with the following output:

uid | switches

Where switches refers to the number of occurrences in the switched table. Could someone please guide me on how to do this using MySQL and PHP. I appreciate any help.

Regards,

3
  • does your user table have anything to do with the desired output? Commented Jul 17, 2014 at 14:18
  • Providing sample data and desired output would help better illustrate the problem and desired solution. At this time I can't see why you would need the first table at all. Select UID, count(Switches) from switched group by UID seems like what your after but I can't tell. counting switches means NULL switch_numbers will be omitted if that situation exists. Commented Jul 17, 2014 at 14:18
  • Screenshots would be great... Commented Jul 17, 2014 at 14:18

3 Answers 3

6

This will output the uids found in the switched table and their counts

select uid, count(switch_number) as switches
from switched
group by uid

If you need zero counts too then do

select u.uid, count(s.switch_number) as switches
from users u
left join switched s on s.uid = u.uid
group by u.uid
Sign up to request clarification or add additional context in comments.

Comments

0

try something like that:

select uid, Count(*) from switched Group by uid

Comments

-1

If I understood correctly, you want a GROUP BY clause in your statement.

2 Comments

This is not more than a comment.
Right, sorry for that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.