I've got three tables:
staff
id name
1 Alex
2 John
3 Peter
staff_roles
id role_name
1 Barber
2 Driver
assigned_roles
id staff_id role_id
1 1 1
2 1 2
3 2 1
4 3 2
I want to get output smth. like:
name roles
Alex [{'id':'1','role_name':'Barber'},{'id':'2','role_name':'Driver'}]
John [{'id':'1','role_name':'Barber'}]
Peter [{'id':'2','role_name':'Driver'}]
I'm doing:
SELECT
staff.name,
GROUP_CONCAT(DISTINCT assigned_roles.role_id) as roles
FROM staff
LEFT JOIN assigned_roles
ON assigned_roles.staff_id = staff.id
LEFT JOIN roles
ON roles.id = assigned_roles.role_id
GROUP BY
staff.id
But how can I add role name to GROUP_CONCAT to have the output I want?
You can construct the final result like this:
SELECT s.name,
CONCAT('[',
GROUP_CONCAT(DISTINCT '{''id'':''', ar.role_id, ''',''role_name'':''', r.role_name, '''}'),
']')
FROM staff s LEFT JOIN
assigned_roles ar
ON ar.staff_id = s.id LEFT JOIN
roles r
ON r.id = ar.role_id
GROUP BY s.id;
There might be a typo with all those single quotes and unusual characters.
Related
I have i question about JOINign i have tables User and Category and Request
Id
name
surname
1
Alex
Morgan
2
Tom
Brady
3
Smith
Rowe
Category
Id
Category
1
Party
2
Football match
And now someone create request for another
Request
Id_request
Id_caller
Id_receiver
id_category
1
1
2
1
2
1
3
2
Now i want query to find all request where user 1 (Alex) is caller and get this result
Id_request
Caller_name
Caller_surname
Receiver_name
Receiver _surname
Category
1
Alex
Morgan
Tom
Brady
Party
2
Alex
Morgan
Smith
Rowe
Football match
I try with JOIN but i didn't get this result. Pls help.
You just need to join the tables and take the necessary columns.
However, you need to join the table user twice. When joining a table twice, at least one of them needs to have an alias. The query shown below uses aliases for all tables.
For example, you can do:
select
q.id_request,
c.name as caller_name,
c.surname as caller_surname,
r.name as receiver_name,
r.surname as receiver_surname,
c.category
from request q
join user c on c.id = q.id_caller
join user r on r.id = q.id_receiver -- joined user again with different alias
join category y on y.id = q.id_category
where q.id_caller = 1
You just need two joins, one for the caller and another for the receiver.
select
id_request,
uc.nm_user as "Caller_name",
uc.nm_surname as "Caller_surname",
rr.nm_user as "Receiver_name",
rr.nm_surname as "Receiver_surname",
c.nm_category
from
usr uc
join
request rc on rc.id_caller = uc.id_user
join
usr rr on rr.id_user = rc.id_receiver
join
category c on c.id_category = rc.id_category
where
uc.id_user = 1
Here is the complete example
https://www.db-fiddle.com/f/cA637bx33SFMeDtyUUNqsp/0
You need to join the User table twice with request table -
SELECT R.Id_request,
U1.Caller_name,
U1.Caller_surname,
U2.Receiver_name,
U2.Receiver_surname,
C.Category
FROM Request R
JOIN User U1 ON R.Id_caller = U1.Id
JOIN User U2 ON R.Id_receiver = U2.Id
JOIN Category C ON r.id_category = C.Id;
I have three tables named
**Student Table**
-------------
id name
-------------
1 ali
2 ahmed
3 john
4 king
**Course Table**
-------------
id name
-------------
1 physic
2 maths
3 computer
4 chemistry
**Bridge**
-------------
sid cid
-------------
1 1
1 2
1 3
1 4
2 1
2 2
3 3
3 4
4 1
4 2
Now to show the student name with the course name which he had studied like,
**Result**
---------------------------
Student Course
---------------------------
ahmed physic
ahmed maths
ahmed computer
ahmed chemistry
ali physic
ali maths
john computer
john chemistry
king physic
king maths
I build following query
select s.name as Student, c.name as Course from student s, course c join bridge b on c.id = b.cid order by s.name
But it does not return the required result...
And what would be for normalized form, if I want to find who is manager over other:
**employee**
-------------------
id name
-------------------
1 ali
2 king
3 mak
4 sam
5 jon
**manage**
--------------
mid eid
--------------
1 2
1 3
3 4
4 5
And wants to get this result:
**result**
--------------------
Manager Staff
--------------------
ali king
ali mak
mak sam
sam jon
Use ANSI syntax and it will be a lot more clear how you are joining the tables:
SELECT s.name as Student, c.name as Course
FROM student s
INNER JOIN bridge b ON s.id = b.sid
INNER JOIN course c ON b.cid = c.id
ORDER BY s.name
Simply use:
select s.name "Student", c.name "Course"
from student s, bridge b, course c
where b.sid = s.sid and b.cid = c.cid
For normalize form
select e1.name as 'Manager', e2.name as 'Staff'
from employee e1
left join manage m on m.mid = e1.id
left join employee e2 on m.eid = e2.id
SELECT *
FROM user u
JOIN user_clockits uc ON u.user_id=uc.user_id
JOIN clockits cl ON cl.clockits_id=uc.clockits_id
WHERE user_id = 158
Don't join like that. It's a really really bad practice!!! It will slow down the performance in fetching with massive data. For example, if there were 100 rows in each tables, database server have to fetch 100x100x100 = 1000000 times. It had to fetch for 1 million times. To overcome that problem, join the first two table that can fetch result in minimum possible matching(It's up to your database schema). Use that result in Subquery and then join it with the third table and fetch it. For the very first join --> 100x100= 10000 times and suppose we get 5 matching result. And then we join the third table with the result --> 5x100 = 500. Total fetch = 10000+500 = 10500 times only. And thus, the performance went up!!!
join query with three tables and we want two values from the same column we set the alias name for every table in the joins. Same table name also declare as a different names.
const sql = `select p.ID,p.purchaseamount,urs.name as
buyername,pd.productname,
pd.amount,urs1.name as sellername
from purchases p
left join products pd on p.productid=pd.ID
left join users urs on p.userid=urs.ID
left join users urs1 on pd.userid=urs1.ID`
SELECT
employees.id,
CONCAT(employees.f_name," ",employees.l_name) AS 'Full Name', genders.gender_name AS 'Sex',
depts.dept_name AS 'Team Name',
pay_grades.pay_grade_name AS 'Band',
designations.designation_name AS 'Role'
FROM employees
LEFT JOIN genders ON employees.gender_id = genders.id
LEFT JOIN depts ON employees.dept_id = depts.id
LEFT JOIN pay_grades ON employees.pay_grade_id = pay_grades.id
LEFT JOIN designations ON employees.designation_id = designations.id
ORDER BY employees.id;
You can JOIN multiple TABLES like this example above.
Just adding a point to previous answers that in MySQL we can either use
table_factor syntax
OR
joined_table syntax
mysql documentation
Table_factor example
SELECT prd.name, b.name
FROM products prd, buyers b
Joined Table example
SELECT prd.name, b.name
FROM products prd
left join buyers b on b.bid = prd.bid;
FYI: Please ignore the fact the the left join on the joined table example doesnot make much sense (in reality we would use some sort of join table to link buyer to the product table instead of saving buyerID in product table).
Query for three table join and limit set
SELECT * FROM (SELECT t1.follower_userid, t2.*, t3.login_thumb, t3.login_name,
t3.bio, t3.account_status, t3.gender
FROM videos t2
LEFT JOIN follower t1
ON t1.follower_userid = t2.user_id
LEFT JOIN videos_user t3
ON t1.follower_userid = t3.login_userid
WHERE t1.following_userid='$userid'
LIMIT $startpoint , $limit) AS ID
ORDER BY ID DESC
Query to join more than two tables:
SELECT ops.field_id, ops.option_id, ops.label
FROM engine4_user_fields_maps AS map
JOIN engine4_user_fields_meta AS meta ON map.`child_id` = meta.field_id
JOIN engine4_user_fields_options AS ops ON map.child_id = ops.field_id
WHERE map.option_id =39 AND meta.type LIKE 'outcomeresult' LIMIT 0 , 30
Use this:
SELECT s.name AS Student, c.name AS Course
FROM student s
LEFT JOIN (bridge b CROSS JOIN course c)
ON (s.id = b.sid AND b.cid = c.id);
I have table users:
id name
----- -----
1 Mark
2 John
3 Paul
4 Dave
5 Chris
and table matches:
id sender receiver matched
-- ------ -------- -------
1 2 5 2
2 1 3 0
3 1 2 0
So John have sent 1 request for match and his match is accepted.
Also John have receive 1 match which is still not accepted.
I'm using this code to find the names of the users by their ids
SELECT matches.sender as sender,matches.receiver as receiver,users.name as `userName`,
users.user as `userName2` FROM `matches`
INNER JOIN `users` ON matches.sender = users.id
WHERE '$id' IN (sender,receiver) AND matched='2'
but it's pulling out only sender's userName . When I type
...ON matches.sender = users.id AND matches.receiver = users.id ....
the result is 0
So I need to pull out the names of the 2 people.
I think you want two joins:
select m.*, us.name as sender_name, ur.name as receiver_name
from matches m join
users us
on m.sender = us.id join
users ur
on m.receiver = ur.id
where 2 in (m.sender, m.receiver) and
m.matched = 2;
I have three tables named
**Student Table**
-------------
id name
-------------
1 ali
2 ahmed
3 john
4 king
**Course Table**
-------------
id name
-------------
1 physic
2 maths
3 computer
4 chemistry
**Bridge**
-------------
sid cid
-------------
1 1
1 2
1 3
1 4
2 1
2 2
3 3
3 4
4 1
4 2
Now to show the student name with the course name which he had studied like,
**Result**
---------------------------
Student Course
---------------------------
ahmed physic
ahmed maths
ahmed computer
ahmed chemistry
ali physic
ali maths
john computer
john chemistry
king physic
king maths
I build following query
select s.name as Student, c.name as Course from student s, course c join bridge b on c.id = b.cid order by s.name
But it does not return the required result...
And what would be for normalized form, if I want to find who is manager over other:
**employee**
-------------------
id name
-------------------
1 ali
2 king
3 mak
4 sam
5 jon
**manage**
--------------
mid eid
--------------
1 2
1 3
3 4
4 5
And wants to get this result:
**result**
--------------------
Manager Staff
--------------------
ali king
ali mak
mak sam
sam jon
Use ANSI syntax and it will be a lot more clear how you are joining the tables:
SELECT s.name as Student, c.name as Course
FROM student s
INNER JOIN bridge b ON s.id = b.sid
INNER JOIN course c ON b.cid = c.id
ORDER BY s.name
Simply use:
select s.name "Student", c.name "Course"
from student s, bridge b, course c
where b.sid = s.sid and b.cid = c.cid
For normalize form
select e1.name as 'Manager', e2.name as 'Staff'
from employee e1
left join manage m on m.mid = e1.id
left join employee e2 on m.eid = e2.id
SELECT *
FROM user u
JOIN user_clockits uc ON u.user_id=uc.user_id
JOIN clockits cl ON cl.clockits_id=uc.clockits_id
WHERE user_id = 158
Don't join like that. It's a really really bad practice!!! It will slow down the performance in fetching with massive data. For example, if there were 100 rows in each tables, database server have to fetch 100x100x100 = 1000000 times. It had to fetch for 1 million times. To overcome that problem, join the first two table that can fetch result in minimum possible matching(It's up to your database schema). Use that result in Subquery and then join it with the third table and fetch it. For the very first join --> 100x100= 10000 times and suppose we get 5 matching result. And then we join the third table with the result --> 5x100 = 500. Total fetch = 10000+500 = 10500 times only. And thus, the performance went up!!!
join query with three tables and we want two values from the same column we set the alias name for every table in the joins. Same table name also declare as a different names.
const sql = `select p.ID,p.purchaseamount,urs.name as
buyername,pd.productname,
pd.amount,urs1.name as sellername
from purchases p
left join products pd on p.productid=pd.ID
left join users urs on p.userid=urs.ID
left join users urs1 on pd.userid=urs1.ID`
SELECT
employees.id,
CONCAT(employees.f_name," ",employees.l_name) AS 'Full Name', genders.gender_name AS 'Sex',
depts.dept_name AS 'Team Name',
pay_grades.pay_grade_name AS 'Band',
designations.designation_name AS 'Role'
FROM employees
LEFT JOIN genders ON employees.gender_id = genders.id
LEFT JOIN depts ON employees.dept_id = depts.id
LEFT JOIN pay_grades ON employees.pay_grade_id = pay_grades.id
LEFT JOIN designations ON employees.designation_id = designations.id
ORDER BY employees.id;
You can JOIN multiple TABLES like this example above.
Just adding a point to previous answers that in MySQL we can either use
table_factor syntax
OR
joined_table syntax
mysql documentation
Table_factor example
SELECT prd.name, b.name
FROM products prd, buyers b
Joined Table example
SELECT prd.name, b.name
FROM products prd
left join buyers b on b.bid = prd.bid;
FYI: Please ignore the fact the the left join on the joined table example doesnot make much sense (in reality we would use some sort of join table to link buyer to the product table instead of saving buyerID in product table).
Query for three table join and limit set
SELECT * FROM (SELECT t1.follower_userid, t2.*, t3.login_thumb, t3.login_name,
t3.bio, t3.account_status, t3.gender
FROM videos t2
LEFT JOIN follower t1
ON t1.follower_userid = t2.user_id
LEFT JOIN videos_user t3
ON t1.follower_userid = t3.login_userid
WHERE t1.following_userid='$userid'
LIMIT $startpoint , $limit) AS ID
ORDER BY ID DESC
Query to join more than two tables:
SELECT ops.field_id, ops.option_id, ops.label
FROM engine4_user_fields_maps AS map
JOIN engine4_user_fields_meta AS meta ON map.`child_id` = meta.field_id
JOIN engine4_user_fields_options AS ops ON map.child_id = ops.field_id
WHERE map.option_id =39 AND meta.type LIKE 'outcomeresult' LIMIT 0 , 30
Use this:
SELECT s.name AS Student, c.name AS Course
FROM student s
LEFT JOIN (bridge b CROSS JOIN course c)
ON (s.id = b.sid AND b.cid = c.id);
I have four tables
users
ID display_name
1 Name1
2 Name2
3 Name3
A user can add books to table books
books
book_id AddedByuserID
1 1
2 1
3 2
4 3
Also a user can add ebooks to table ebooks
ebooks
ebook_id AddedByuserID
1 1
2 2
3 2
4 3
Now a user can add books only to his collection (not ebooks)
collection
userID book_id
1 1
1 2
1 3
I need an output like this:
display_name books_added ebooks_added books_in_collection
Name1 2 1 3
Name2 1 2 2
Name3 1 1 1
This is what got:
SELECT users.*, COUNT(DISTINCT collection.book_id) AS books_in_collection, COUNT(DISTINCT books.AddedByuserID) AS books_added, COUNT(DISTINCT ebooks.AddedByuserID) AS ebooks_added
FROM users LEFT JOIN collection ON users.ID = collection.userID
LEFT JOIN books ON users.ID = books.AddedByuserID
LEFT JOIN ebooks ON users.ID = ebooks.AddedByuserID
GROUP BY users.ID
ORDER BY display_name ASC
The user display_name gets displayed correct and also the collection count, but the two other counts are showing 1.
If I remove DISTINCT the collection count says 86, and the two other counts show nothing.
I try to understand LEFT join and read tutorials but i'm stuck at the moment.
I would suggest correlated subqueries:
select u.*,
(select count(*) from collection c where u.id = c.userId) as books_in_collection,
(select count(*) from books b where u.id = b.AddedByUserId) as books_added,
(select count(*) from ebooks e where u.id = e.AddedByUserId) as ebooks_added
from users u;
I don't know why you are filtering out the third user, however.