SQL: Combine results of queries [duplicate] - mysql

This question already has answers here:
How to join two tables mysql?
(4 answers)
Closed 1 year ago.
I have 2 tables as such:
StudentID
Email
1
him#school.edu
2
her#school.edu
Book Title
Borrowed By (Student ID)
Borrowed Date
Some Book
13
10/10/2021
Other Book
456
10/15/2021
I want to make a single SQL query to return the email of the student and borrowed date for a specific book title.
Something like
SELECT
*
FROM
student_table
WHERE
StudentID = (SELECT
StudentID
FROM
borrowed_table
WHERE
BookTitle = 'Some Book');
but this would only return the Email. I want to return the borrowed date as well.
How can I combine the results of both queries?
Can this be done without specifying the columns (UNION of *) ?

Join both tables
SELECT
st.*,bt.`Borrowed Date`
FROM
student_table st
INNER JOIN borrowed_table bt ON st.StudentID = bt.StudentID
WHERE
bt.BookTitle = 'Some Book';

Select st.BookTitle, st.BorrowedBy, bt.BorrowedDate
from Student_table st inner join
borrowed_table bt on st.StudentID = bt.StudentID
where bt.BookTitle = 'Some book title'

Related

MySQL - query that should filter based on records contained in the join table [duplicate]

This question already has answers here:
Left Outer Join doesn't return all rows from my left table?
(3 answers)
Closed 6 months ago.
studentTable:
id
studentName
1
Name1
2
Name2
3
Name3
studentCourseTable:
id
studentId
courseId
1
1
1
2
1
2
3
3
1
4
3
3
5
2
2
I want to (let's say) list students who have taken courseId 1 AND 3 (together) BUT have NOT taken 2. Or any dynamic combination such as that, like courseId 1,2,3 should be taken; 1,2 not taken but 3 is taken etc etc.
I have tried some JOIN clause to filter but have not been able to apply more than 1 condition:
SELECT student.*
FROM studentTable AS s
LEFT JOIN studentCourseTable AS sc
ON sc.studentId = s.id
WHERE sc.studentId IN (1,3)
AND sc.studentId NOT IN (2)
or:
SELECT student.*
FROM studentTable AS s
LEFT JOIN studentCourseTable AS sc
ON sc.studentId = s.id
AND sc.courseId IN (1, 3)
AND sc.courseId IN (2)
The important thing is that I want to find students that take specified courses TOGETHER, AND not take any other specified course. The student may take more courses than specified (as long as it is not in NOT taken list).
**Edit for some clarifications: ** For example if I say the student should take (2,4) but NOT (3), returning a student that takes (2,4,5) is ok. But (2,3) or (2,4,5) are NOT ok.
There are some other tables that I'm joining the student table with, not sure if it matters but this is the gist of it.
Can anyone assist me with this?
** Edit: ** #lemon has cracked it. Here's the demo he made, which lists any user that attended 1 OR 3 AND have not attended 2. Here's my updated demo which lists students that attended 1 AND 3 AND have not attended 2.
Thanks to all who helped me, this was superb.
You can select all information from your students and use two kind of JOIN operations:
an INNER JOIN for each due attended course
a LEFT JOIN for non-attended courses, to be filtered out in the WHERE clause
SELECT s.*
FROM students s
INNER JOIN (SELECT DISTINCT studentId FROM courses WHERE courseId = 1) c1
ON s.id = c1.studentId
INNER JOIN (SELECT DISTINCT studentId FROM courses WHERE courseId = 3) c3
ON s.id = c3.studentId
LEFT JOIN (SELECT DISTINCT studentId FROM courses WHERE courseId IN (2)) not_c
ON s.id = not_c.studentId
WHERE not_c.studentId IS NULL
Check the demo here.
Another option is to count
positively your needed courses
negatively your unneeded courses
Eventually sum up the values, and filter out those students whom don't have sum equal to the amount of needed courses.
SELECT s.*
FROM courses c
INNER JOIN students s
ON s.id = c.studentId
GROUP BY s.id,
s.studentName
HAVING SUM(CASE WHEN c.courseId IN (1,3) THEN 1
WHEN c.courseId IN (2) THEN -1 END) = 2
Check the demo here.
To get only students that are in groups 1 and 3
SELECT s.studentName
from studenttable AS s
INNER JOIN studentCourseTable AS sc ON sc.studentId = s.id
where sc.courseId in (1,3)
group by s.id
having count(*) = 2;
We first should group by student name or id, then we get only those that are in the 2 courses by adding "having count(*) = 2"

Joining four tables with left or right join [duplicate]

This question already has an answer here:
LEFT JOIN does not return all the records from the left side table
(1 answer)
Closed 4 years ago.
I have four tables.
Level Table levels(id, name)
Student Table students(id, name, level_id)
Subject Table subjects(id, name)
Report Table reports(id, student_id, subject_id, test, exam)
I need a single query that will fetch results(report table) for a single level(e.g id=1 for Class One) and a particular subject(e.g id=2 for like English)
I have this query:
select name, test, exam
from `reports`
right join `students`
on `reports`.`student_id` = `students`.`id`
where `students`.`level_id` = '1'
and `reports`.`subject_id` = '2'
But it's only showing result for records that are inside the reports table. Am expecting all data from the students table where the level_id is specified but with NULL from their test and exam row if they don't have record in the results table.
The main issue is the subject_id clause(and reports.subject_id = '2') on the query. It's only working for record if present in the records table Here is the result
When I used subject_id that's not in the result table Here is the result -not returning anything
But it's only showing result for records that are inside the reports table
Not strictly true - its only showing results where reports.subject_id = '2'. If there is no matching row in the reports table, then the subject_id would be null, and null is not equal to 2.
You need to specify the predicate for the reports table in the join clause, not in the where clause, to get all the students:
select name, test, exam
from `reports`
right join `students`
on `reports`.`student_id` = `students`.`id`
and `reports`.`subject_id` = '2'
where `students`.`level_id` = '1'
you can try below statement to get all student with level=1
select name
, test
, exam
from students
join reports
on students.id = reports.student_id
and reports.subject_id = 2
where students.level_id = 1

Mysql SELECT eliminate rows duplicate values in one column (joining 2 tables)

This is a different question because I have joined 2 tables. The solutions for the duplicate question indicated does not work for me.
This is the query:
SELECT a.id, a.userName, IF(o.userId = 1, 'C', IF(i.userId = 1,'I','N')) AS relation
FROM tbl_users AS a
LEFT JOIN tbl_contacts AS o ON a.id = o.contactId
LEFT JOIN tbl_invites AS i on a.id = i.invitedId
ORDER BY relation
This returns the output as follows:
id username relation
1 ray C
2 john I
1 ray N
I need to remove the third row from the select query by checking if possible that id is duplicate. I tried adding distinct(a.id) but it doesn't work. How do I do this?

Mysql query to retrive data from join of three table [duplicate]

This question already has answers here:
MySQL pivot row into dynamic number of columns
(1 answer)
MySQL - Rows to Columns
(13 answers)
Closed 5 years ago.
I have tree tables:
Persons:
id
name
Books
id
title
Quantity:
People_id
Product_id
quantity
I need a result with :
in the columns the Book title, in the rows the Persons name, in the cells the quantity take from the cross of peoples and books
select *
from persons p join quantity q on p.id = q.people_id
join books b on q.product_id = b.id
JOIN should help (if you need columns from all table then add alias.* for other tables in SELECT).
SELECT p.*
FROM persons p
JOIN quantity q ON p.id = q.people_id
JOIN books b ON q.product_id = b.id

Join 2 column same table with another column [duplicate]

This question already has answers here:
How to join two columns to the same table [duplicate]
(3 answers)
Closed 5 years ago.
I want to join 2 column that share same foreign key in another table
here's the tables:
country:
idcountry| countryname
1 german
2 america
destination
id|fromcountry |tocountry
1 1 2
the result that i wanted to:
id|fromc |toc
1 german america
Use simple Left Join ans provide alias to country name column:
SELECT d.idcountry as id, cf.CountryName as fromc, ct.CountryName as toc
FROM destination d
LEFT JOIN country cf ON d.fromcountry = cf.idcountry
LEFT JOIN country ct ON d.tocountry = ct.idcountry
Use Left Outer Join for both fields
something like this
SELECT Dest.ID, CFrom.CountryName, CTo.CountryName
FROM Destination Dest
LEFT OUTER JOIN Country CFrom ON Dest.FromCountry = CFrom.idcountry
LEFT OUTER JOIN Country CTo ON Dest.ToCountry = CTo.idcountry