MySQL join multiple columns from same table - mysql

I am trying to write a query that returns a users profile information, along with a count of occurrences of the user's ID in 2 columns from another table. An example below:
TableA
userID userName
1 UserA
2 UserB
TableB
LinkID leadID followID
1 1 2
2 1 3
3 2 1
Querying against UserID 1 I would expect to retrieve UserA, 2 (occurences of 1 in leadID), and 1 (occurences of 1 in followID). Any help with this is much appreciated, and thanks in advance.

You don't actually need to join for this - you can instead make three separate selects.
SELECT
(
SELECT userName
FROM TableA
WHERE userID = 1
) AS userName,
(
SELECT COUNT(*)
FROM TableB
WHERE leadID = 1
) AS count_leadID,
(
SELECT COUNT(*)
FROM TableB
WHERE followID = 1
) AS count_followID
Result:
userName count_leadID count_followID
UserA 2 1

SELECT a.userName,
SUM(IF(b.leadId = a.userId, 1, 0) as Leads,
SUM(IF(b.followId = a.userId, 1, 0) as Follows
FROM TableA a
TableB b
GROUP BY a.userName

SELECT a.userName,
b1.count(*) as leads,
b2.count(*) as follows
FROM TableA a
INNER JOIN TableB b1 on a.userID = b1.leadID
INNER JOIN TableB b2 on a.userID = b2.followID
GROUP BY a.userName
Depending on how mySQL optimizes and if you have an index on leadID and followID then this could speed up the query, especially if you're going to query just a few users rather than them all at the same time.

Related

Retrieve data using joins with multiple conditions

I am trying to write a query which retrieves data from a table which doesn't have data on another table.
I have table A with values
ID StudentID CLASSID
1 1 2
2 2 3
3 3 4
4 4 5
TABLE B with values
ID StudentID CLASSID
1 1 2
2 2 3
I am trying to return values from table A with ID 3,4 which is not available in TABLE B.
Query I have tried is
SELECT *
FROM A AS a
WHERE NOT EXISTS
(
SELECT *
FROM B AS b
WHERE a.student_id = b.student_id
AND a.CLASSID = b.CLASSID
);
NOTE: As my problem was slow query. I have fixed this problem by creating index which made this query run fast.
Thanks for your effort.
Using LEFT OUTER JOIN
SELECT TableA.* FROM TableA
LEFT OUTER JOIN TableB
ON TableA.ID = TableB.ID
WHERE TableB.ID IS null
Using NOT IN
SELECT * FROM TableA
WHERE TableA.ID NOT IN ( SELECT ID FROM TableB)
Using NO EXISTS
SELECT *
FROM tableA a
WHERE NOT EXISTS
(
SELECT 1
FROM tableB b
WHERE a.studentsID = b.studentsID
AND a.CLASSID = b.CLASSID
);

How to get two tables data using single mysql query?

Following is my tables which is student id is common field in both tables. I want to get both tables data in single query.Also get recent data of student.
table A:
student_id name surname email
------------------------------------------------
1 ABC LLL abc#gmail.com
2 PQR SSS pqr#gmail.com
Table B:
student_id Assignment_Id Assignment_Name last_submited
---------------------------------------------------------------------
2 1 asign_1 sub_0001
1 2 asign_2 sub_0002
2 3 asign_2 sub_0003
I want exact output like:-
student_id Assignment_Id email last_submited
--------------------------------------------------------------
2 3 pqr#gmail.com sub_0003
I have used following query for getting recent record but confused how to get email id along with this.
SELECT assignment_id,
student_id,
last_submited
FROM tableB
WHERE student_id= '2'
ORDER BY assignment_id DESC LIMIT 1
You can make use of a JOIN
select tableB.assignment_id,
tableB.student_id,
tableB.last_submited,
tableA.email
from tableB INNER JOIN
tableA ON tableB.student_id = tableA.student_id
where tableB.student_id= '2'
order by tableB.assignment_id desc
limit 1
INNER JOINs are used to return data where the data is in both tables (so en entry would exist in tableA and tableB).
LEFT JOINs are used when you wish to retrieve all data from tableA and those values that are available in tableB.
So, lets say you had
TABLEA
-------
1
2
and
TABLEB
-------
1
SELECT *
FROM TABLEA INNER JOIN
TABLEB ON TABLEA.ID = TABLEB.ID
would return
1,1
Whereas
SELECT *
FROM TABLEA LEFT JOIN
TABLEB ON TABLEA.ID = TABLEB.ID
would return
1,1
2,NULL
You need to use join
SELECT a.student_id,
b.Assignment_id,
a.email,
b.last_submitted
FROM a
INNER JOIN b ON a.student_id = b.student_id
WHERE a.student_id= '2'
ORDER BY b.assignment_id DESC LIMIT 1
Join both the tables,
SELECT B.assignment_id,
B.student_id,
A.email_id ,
B.last_submited
FROM tableB 'B',
tableA 'A'
WHERE B.student_id= '2'
AND A.student_id=B.student_id
ORDER BY assignment_id DESC LIMIT 1

MYSQL get all id using parentid and id

I am trying to get all id under a typeid using id i want to use just one query to do this it can be done with an inner query like this.
SELECT id FROM users where typeId = (SELECT typeId FROM users where id = 5)
This will give me what i want but i have heard that inner query is slow so i would like to do this using join query.
users
id typeid name
1 2 a
2 2 b
3 1 c
4 3 d
5 3 e
That will be:
SELECT
a.id
FROM
users AS a
LEFT JOIN users AS b
ON a.typeId=b.typeId
WHERE
b.id = 5
-check this fiddle.
What you want I don't know with this query:
SELECT id FROM users where typeId = (SELECT typeId FROM users where id = 5)
You can simply write this query as:
SELECT t1.id
FROM users AS t1
LEFT JOIN users AS t2
ON t1.typeId = t2.typeId
WHERE t2.id=5
BUT I exclaimed that when you know id then why are you using the query to fetch the same id again. I think you are lacking some information.

Select Group by from Same Table

I have a table users like this:
id user refid
1 a null
2 b 1
3 c 1
4 d 2
5 f 3
I need to select the users, grouping by refid and the count of each refid for each user. For example,
id user count
1 a 2
2 b 1
3 c 1
This is what I have tried:
SELECT user, refid, count(*) cnt FROM `users` group by refid
However, this gives me the wrong user for each value. How can I get the correct user for each value?
I guess this is what you're looking for. Basically, you're missing a join there.
select u1.id, u1.user, count(u1.id) cnt from mlm_users u1
join mlm_users u2 on u1.id = u2.refid
group by u1.id, u1.user
This will return the id, user and the amount of referrals each of them have (only for the ones that have at least one referral).
You need to group by the user and refid
SELECT user, refid, count(*) cnt FROM `mlm_users` group by user,redid

mysql left join returns unexpected amount of rows

I have 2 tables where
tableA has 41 rows
and
tableB has 3 rows
I am trying to get the total rows of these 2 tables via a query using left join but i get way more rows(123) than expected(44)
query:
SELECT COUNT(*)
FROM tableA as u
LEFT JOIN tableB as d
ON u.uid=d.uid
WHERE
u.uid=912391178669
AND
u.deleted = 0
AND
d.deleted=0
tables schema:
tableA
id | uid | deleted
tableB
id | uid | deleted
I have run the following query It is working correctly.. U can check it out.
SELECT
( SELECT count(*) from table1 where.... )
+ ( SELECT count(*) from table2 where.... )
as total from dual
I'm guessing that you have three rows in tableA with the uid given in the query. That will mean that each row in tableA will join once with each row in tableB, which means you will back 41 x 3 rows or 123.
From the number of rows you are expecting back, I wonder if you need a Union instead of a join.
Select * from tableA where uid = 912391178669 and deleted = 0
union all
Select * from tableB where uid = 912391178669 and deleted = 0
A union will combine the results of two queries. A join will combine the columns of table tables in a single query.
41*3=123
each row of TableA has uid=912391178669 and tableB each row also have uid that's why you are getting 123 row total. use some filter criteria to get desired result (like some AND condition)
if you can show us your table column then it may be possible to help you .
Left join does not combine the rows of two table .
TableA left join TableB will give you all the row of table A meeting the joining condition.
SELECT COUNT(*)
FROM tableA as u
LEFT JOIN tableB as d
ON u.uid=d.uid
AND
u.deleted = d.deleted
WHERE
u.uid=912391178669
AND u.deleted = 0
SELECT SUM(
(SELECT count(*) from tableA WHERE uid=912391178669)
+ (SELECT count(*) from tableA WHERE uid=912391178669)
) as totalRows