MySQL SELECT IF statement - mysql

I have 4 tables; loans (has 'user_id'), users (has 'student_ID' and 'teacher_ID'), student, and teacher.
The code I tried:
SELECT *FROM loans LEFT JOIN users ON loans.user_id=users.user_id
(
IF student_ID='1' THEN (SELECT *FROM teacher)
ELSE (SELECT *FROM student)
)
The code is not working properly. I want the loans display the student or teacher name from users. I have tried similia work, and it doesn't work either.

Try this:
select *
from loans l
left join users u on l.user_id = users.user_id
left join teacher t on u.teacher_id = t.teacher_id and u.student_id = 1
left join student s on u.student_id = s.student_id and u.student_id <> 1
Explanation
Extract every record in loans
Extract records in users where there's a match on user_id
Extract records from teacher matching on teacher_id if user's student_id is 1
Extract records from student matching on student_id if user's student_id is NOT 1

Related

SQL LEFT JOIN for all records of first table and matched records of another table

I have 3 tables.
Table seller with columns like id, name etc.
Table customer like id, name etc.
Table connections which have seller_id, customer_id, status of friendship like "friends", "pending_request" etc.
Now I want to get all the sellers who are not friends of a specific customer.
So I tried like fetching records from seller table with left join of connections table, with condition status is not "friends"
I tried the following query but didn't help me. I also tried other queries but didn't help.
SELECT * FROM `seller` LEFT JOIN `connections` ON seller.user_id = connections.user_id WHERE customer_id = 10 AND request_status NOT LIKE "friends"
Here is the reference screen I want the result. Like for a particular customer, all the sellers who are not friends or request is pending.
Join the connections of type 'friends' for customer_id = 10 and in a WHERE clause check for the connections.user_id being NULL, i.e. nothing has been joined.
SELECT *
FROM seller
LEFT JOIN connections
ON seller.user_id = connections.user_id
AND connections.customer_id = 10
AND connections.request_status = 'friends'
WHERE connections.user_id IS NULL;
Or use a correlated subquery, that gets the connection with a NOT EXISTS.
SELECT *
FROM seller s
WHERE NOT EXISTS (SELECT *
FROM connections c
WHERE c.user_id = s.user_id
AND c.customer_id = 10
AND c.request_status = 'friends');
Try this:
SELECT * FROM `seller` LEFT JOIN `connections` ON seller.user_id = connections.user_id WHERE customer_id = 10 AND (request_status NOT LIKE "friends"
or request_status is null)
Or this:
SELECT * FROM `seller` LEFT JOIN `connections` ON seller.user_id = connections.user_id WHERE customer_id = 10 AND IFNULL(request_status,"other") NOT LIKE "friends"

MySQL Multiple Joins 3 Table ( Bridge Table )

1st table Courses columns:
courseId|instructorId|desc|courseName|img|
2nd table StudentCourses columns:
studentCourseId|studentId
3rd table UserData columns:
userId|avatar|name
So knowing studentId,i am trying to get students owned courses with its instructors profiledata(in this case avatar and name)
result columns should be:
courseId,courseName,desc,img,instructorsname,instructorsavatar
This query gives me students courseInfo but instructor data is not included.
SELECT Courses.courseId,Courses.img,Courses.courseName,Courses.`desc` FROM Courses JOIN StudentCourses ON StudentCourses.studentCourseId = Courses.courseId WHERE StudentCourses.studentId ="igkw11tkwa06kpmoe9o6hyytrq0qaqjq"
assuming that instructorId match with userid
SELECT Courses.courseId
,Courses.img
,Courses.courseName
,Courses.`desc`
, u1.name
, u1.avatar
FROM Courses
INNER JOIN StudentCourses ON StudentCourses.studentCourseId = Courses.courseId
INNER JOIN UserData u1 ON u1.userId = Courses.instructorId
WHERE StudentCourses.studentId ="igkw11tkwa06kpmoe9o6hyytrq0qaqjq"

Return all courses a student is taking (Many to Many SQL Database example)

I'm fairly new to MySQL, and trying to understand the many-to-many relationship since these examples can popup in interviews
There are 3 tables, and since a Student can have many courses and a Course can have many students, this is a Many-to-Many relationship right?
The tables are
Student- has student ID, name, date of birth, and department.
Courses- Has ID, Name of course
Student_Courses- Has student_id, course_id
How would I display these 2 questions-
1) Given a studentID, return all the names of the courses the student is taking
2) Return the name of students who is taking X amount of courses or more (Ex. 4 or more courses).
Im trying to write queries on these, but I'm stuck...
In the case of selecting all of the courses for a given student ID you could try the following, which will return one row for each Course a Student is associated with.
select
s.name as StudentName,
c.name as CourseName
from `Student` as s
inner join `Student_Course` as sc on (sc.student_id = s.ID)
inner join `Course` as c on (c.ID = sc.course_id)
where
(s.`ID` = 'given_Student_ID_here')
;
As for selecting a list of the names of Students taking N or more courses, for this you might use an aggregating sub-select as a WHERE clause in which we reference one of the outer tables (i.e. [Student]) so that the result of the aggregation is personalised per Student record:
select
s.name as StudentName
from `Student` as s
where
(
(
select count(*)
from `Student_Course` as sc
inner join `Course` as c on (c.ID = sc.course_id)
where (sc.student_id = s.ID)
) >= 4
)
;
You might also consider an alternative approach to this second problem by using the GROUP BY and HAVING clauses:
select
s.name as StudentName
from `Student` as s
inner join `Student_Course` as sc on (sc.student_id = s.ID)
inner join `Course` as c on (c.ID = sc.course_id)
group by
s.name
having
count(*) >= 4
;

Mysql: count and group unique emails in associated tables by polymorphic join

The relevant part of my schema (Mysql 5.6.24) is thus:
table: training_event_invitees
registered (tinyint)
invitee_id (id)
invitee_type (varchar)
table: users
id (integer)
email (varchar)
school_id (integer)
table: contacts
id (integer)
email (varchar)
school_id (integer)
table: schools
id (integer)
email (varchar)
I want to try to do the following: get all the training_event_invitees that have registered set to 1, get the associated school, user and contact records, and then group them by school_id, and return the school id and the count of unique email addresses from that school.
training_event_invitees has a two-column foreign key, using invitee_id and invitee_type: invitee_type would be either "School", "User" or "Contact", and references the id field from the corresponding table.
So, algorithmically, it's something like
- get all the registered training_event_invitees
- get all of the associated user, contact and school records
- group these by users.school_id, contacts.school_id or schools.id
- count the number of distinct emails in each group
So, it should return an array like
[
[1234, 6],
[3407, 2]
]
where 1234 and 3407 are values of school_id and 6 and 2 are the count of distinct emails.
I can break this down into a few steps, but there must be a one-hit way to do it. Can anyone help?
One method is to combine the two tables using left join, and then doing the aggregation:
select coalesce(u.school_id, c.school_id) as school_id,
count(distinct coalesce(u.email, c.email)) as num_emails
from training_event_invitees tei left join
users u
on u.id = tei.invitee_id and tei.invitee_type = 'user' left join
contacts c
on c.id = tei.invitee_id and tei.invitee_type = 'contact'
where tei.registered = 1
group by coalesce(u.school_id, c.school_id);
EDIT:
To include the school, follow the same logic:
select coalesce(u.school_id, c.school_id, s.id) as school_id,
count(distinct coalesce(u.email, c.email, s.email)) as num_emails
from training_event_invitees tei left join
users u
on u.id = tei.invitee_id and tei.invitee_type = 'user' left join
contacts c
on c.id = tei.invitee_id and tei.invitee_type = 'contact' left join
schools s
on s.id = tei.invitee_id and tei.invitee_type = 'school'
where tei.registered = 1
group by coalesce(u.school_id, c.school_id, s.id);

How can I search through members that aren't friends of the current user in MySQL?

I have a members table and a member requests table. In the requests table are columns for author id and recipient id and also status. If the current user has a row with their ID as the author id and another member as the recipient id(or vice versa) and the status is 1, then the user is friends with that member. I would like to set up a search system that can be used to find members that the user isn't friends with by the name they type in. The query below is used to find the user's current friends by a name they type in. How can I search through members that the user isn't friends with?
SELECT
r.author_id, m.member_id, m.display_name
FROM member_requests AS r
LEFT JOIN members AS m ON m.member_id = r.author_id
WHERE r.recipient_id = 1
AND r.status = 1
AND m.display_name LIKE "John%"
UNION SELECT
r.recipient_id, m.member_id, m.display_name
FROM member_requests AS r
LEFT JOIN members AS m ON m.member_id = r.recipient_id
WHERE r.author_id = 1
AND r.status = 1
AND m.display_name LIKE "John%"
http://sqlfiddle.com/#!2/eb0d4d/3
This one is a lot easier than you think. Based off my answer from the last question, if you have a list of members someone IS friends with, you can search the members table for IDs that are not in that list.
Try this:
SELECT member_id
FROM members
WHERE member_id NOT IN(
SELECT recipient_id AS friends
FROM member_requests
WHERE author_id = 1 AND status = 1
UNION
SELECT author_id AS friends
FROM member_requests
WHERE recipient_id = 1 AND status = 1)
AND member_id != 1;
SQL Fiddle.