row count on inner join - mysql

ok i've been trying for 2 days to figure this out. I have 2 tables
Organization_dep
id
orgid
depname
organization_dep_users
id
orgid
depid
userid
I want to list the count of user ids from the departments of the organizations.

Can you try this:
SELECT
b.depname, count(a.id)
FROM organization_dep_users a
INNER JOIN Organization_dep b ON a.depid = b.id
GROUP BY b.depname;
Edit:
Thanks for Barmar for additional details.

Related

How to Join three tables properly

The main table has 4 columns:
User Activity Table
userActivityId userId therapistId activityId
1 1 1 1
Each of these columns is a table and these values are all foreign keys.
Basically im trying to run a query that will join to the users table and pull their first and last name based off the user Id.Same thing with therapist - join to the therapist table, pull first + last name.And finally Join to the Activity table and pull the activity name and path from the activity Id
The other tables look like this:
User Table
userId fName lName
Therapist Table
therapistId therapistFirstName therapistLastName
Activity Table
activityId activityTitle activityPath
So far my query looks like
SELECT
User_Activities.userId,
User_Activities.therapistId,
User_Activities.activityId,
Activities.activityTitle,
Activities.activityPath,
Users.fName,
users.lName,
Therapists.therapistFirstName,
Therapists.therapistLastName
FROM
User_Activities
INNER JOIN Users
ON User_Activities.userId = Users.userId
INNER JOIN Therapists ON
User_Activities.therapistId = Therapists.therapistId
INNER JOIN Activities ON
Activities.activityId = User_Activities.userActivityId
WHERE
User_Activities.userId = 1;
When I run this query It only returns 1 row as a result. However there are two activities in the User_Activites table assigned to userId 1.
If I change : INNER JOIN Activities ON
Activities.activityId = User_Activities.userActivityId
from an INNER JOIN to the LEFT JOIN it will display the second row, however the activityTitle and activityPath will be displayed as NULL in the second row.
userActivityId userId therapistId activityId activityId activityTitle activityPath fName lName therapistFirstName therapistLastName
1 1 1 1 1 Brain GZZ0zpUQ S C M D
11 1 1 1 NULL NULL NULL S C M D
You have pretty much answered your question. The second activity does not have a valid ActivityId.
If you want all activities for a user, then you should phrase the query as:
SELECT . . .
FROM Users u LEFT JOIN
User_Activities ua
ON ua.userId = u.userId LEFT JOIN
Therapists t
ON ua.therapistId = t.therapistId LEFT JOIN
Activities a
ON a.activityId = ua.userActivityId
WHERE u.userId = 1;
You want to start with the table where you want to keep all the rows. Then use LEFT JOIN to bring in other tables.
Two other changes of note:
Table aliases are used to simplify reading and writing the query. The SELECT needs to change to use the aliases.
The WHERE clause refers to the Users table rather than UserActivities.

SQL inner join wrong output from two tables

Students Table:
ID | Family_ID | Student_name | F_name
Families Table:
ID | F_name | Contact_No
i want to get all records from students where family_id is repeating.(basically i want to know students Brothers/Sisters records if there is any in student table.
i tried it this way but got wrong output;
SELECT students.*
FROM students
INNER JOIN families
ON families.id = students.family_id
ORDER BY families.id ASC
my query result in image: as you can see some ids are showing once others are more then once, but i think all should appear more then once.
If you want to see only relevant people you don't need to link it to the families table. You can group the student with family_id. Here is your query :
SELECT *
FROM Student
WHERE family_id IN (SELECT family_id
FROM students
GROUP BY family_id
HAVING COUNT(1)>1)
ORDER BY family_id
You could try using a join on subquery for the family_id that have more that one rows in students
SELECT students.*
FROM students
inner join (
select students.family_id
FROM students
group by students.family_id
having count(*)>1
) t on t. family_id = students.family_id

MySQL get count from two related tables

I am using MySQL and database server and I have two tables one is for customer and another for customer_contacts.
Here are the table structures:
customer(
id(pk, ai)
name
email
)
and
customer_contacts(
id(ai)
customer_id
first_name
last_name
)
Now my question is:
lets say I have one customer has many customer_contacts like this
customer
id name email
1 john john#example.com
and customer_contacts is like this (first row)
id customer_id first_name last_name
1 1 john doe
2 1 johnp pual
like this
So here I want to get all the contact details count for the id john. So can some one tell me how to get that?
Any help and suggestions will be really appreciable. Thanks
If the id is already known (as suggested by the question, it would be a plain
SELECT COUNT(*) from customer_contacts
WHERE customer_contacts.id = 1;
You just need to know the number of contactacs for the customer John, right?
SELECT COUNT(*)
FROM customer cus INNER JOIN customer_contacts con ON cus.id = con.customer_id
WHERE cus.name = 'john'
Nevertheless, It would be better if you know the id of John. Your query would be this:
SELECT COUNT(*)
FROM customer_contacts
WHERE customer_id = 1
Simply join both tables and use count() with group by c.id use where to filter records
select c.*,
count(*) total_contacts
from customer c
left join customer_contacts cc on(c.id = cc.customer_id)
group by c.id
Fiddle Demo

Joining Tables in MySQL

I have two tables namely Students & Hobbies with following structure and records:
ID,Name
-----------
9,Peter
10,Steve
ID,Hobby
-----------------
9,dancing
9,singing
10,learning
I want to JOIN these tables and get a unique record from table Students.
I am doing this right now which evolves duplicate records:
SELECT a.Name
FROM Students a
LEFT JOIN Hobbies h ON a.ID =h.ID
This gives :
Name
----------
Peter
Peter
Steve
I got the reason, this is because, the table Hobbies has two records of ID=9 , that is why duplicate records are evolved, but how to retrieve a single record? Please help.
I want this:
Name
-----------
Peter
Steve
SELECT a.ID, a.Name
FROM Students a
LEFT JOIN Hobbies h
ON a.ID = h.ID
GROUP BY a.ID, a.Name
With the GROUP BY, you could then answer questions like "How many hobbies does each student have?"
SELECT a.ID, a.Name, COUNT(*) AS Number_of_Hobbies
FROM Students a
LEFT JOIN Hobbies h
ON a.ID = h.ID
GROUP BY a.ID, a.Name
This is really not the way a JOIN should be used.
left joining an unreferenced table on a constant gets you nothing.
the answer to the question you asked is "use a DISTINCT clause":
SELECT DISTINCT a.Name FROM Students a LEFT JOIN Hobbies h ON a.ID = 9
...but really, I'm pretty sure this is not what you want to do.
based off the comments, I believe what the OP's intent was something like this:
SELECT
a.Name
FROM
Students a
WHERE
a.ID = <Student ID>;
... AND , for the hobbies reference:
SELECT DISTINCT
a.ID,
a.Name
FROM
Students a
INNER JOIN
Hobbies h ON h.ID = a.ID
WHERE
h.Hobby = <Hobby Name>;
Use the distinct keyword:
SELECT distinct a.Name
FROM Students
etc....
It eliminates duplicate rows, so you'll only get one of each name.
You are getting duplicates because Peter has 2 hobbies. If you want a single record per User do this:
select * from Student where Id in (
Select DISTINCT Id from HobbY)

Mysql join query

I have table users and another table premium_users in which I hold the userid and the date when he bought premium membership.
How can I use mysql join , so that in a single query I can select all the columns from the table users and also know for each premium user the date he joined on.
USERS:
ID USERNAME
1 JOHN
2 BILL
3 JOE
4 KENNY
PREMIUM USERS:
ID USERID DATE
1 2 20/05/2010
2 4 21/06/2011
And the final table (the one that will be returned my the query) should look like this:
ID USERNAME DATE
1 JOHN
2 BILL 20/05/2010
3 JOE
4 KENNY 21/06/2011
Is it ok for some rows to have the DATE value empty?
How can I check if that value is empty? $row['date']=='' ?
EDIT:
This was only an example, but the users table has much more columns, how can I select all from users and only date from premium_users without writing all the columns?
select u.*, pu.DATE
from USERS u LEFT OUTER JOIN PREMIUM_USERS pu on
u.ID = pu.USERID
You can check if a row is empty with:
if (!$row['DATE'])
{
...
}
select USERS.ID, USERS.USERNAME, PREMIUM_USERS.DATE
from USERS
join PREMIUM_USERS on USERS.ID = PREMIUM_USERS.ID
order by USERS.ID
This is mssql syntax, but it should be pretty similar...
select *
from users u
left join premiumUsers p
on u.id = p.id
order by u.id asc
SELECT A.*, B.DATE
FROM USERS A
LEFT JOIN PREMIUIM_USERS B on A.ID=B.USERID
EDITED
It might be easier to have it all in one table. You can have nullable fields for isPremium(t/f) and premiumDate. you actually dont even need the isPremium field. just premiumDate if its null they are not premium and if it has value they are premium user and you have the date they joined.