hayleyelisa
hayleyelisa

Reputation: 359

MySQL trying to use INNER JOIN and UNION together?

so basically what I want to do is use INNER JOIN on two tables, but only selecting specific rows from Table A and the corresponding rows from Table B?

Table A is called 'course', and I would want to select entries under the column 'course_title' that are called "Calculus," "British Literature I" and "Studio Art," as well as their corresponding 'department_id', and I would use 'department_id' as the reference for which to create an INNER JOIN with the second table, which is called 'departments,' which has the columns 'department_id' and 'department_name'.

The only way I've thought to do this is by using a UNION to SELECT the three specific courses, but I can't figure out a way to get INNER JOIN to work with that? I've tried several different types of syntax and keep getting errors, here is one of my attempts:

(SELECT course.course_title, cours' at line 1
mysql> (SELECT course_title, department_id FROM course WHERE course_title = 'Calculus')
-> UNION
-> (SELECT course_title, department_id FROM course WHERE course_title = 'British Literature I')
-> UNION
-> (SELECT course_title, department_id FROM course WHERE course_title = 'Studio Art I')
-> UNION
-> (SELECT department_name, department_id FROM departments)
-> FROM departments INNER JOIN course ON departments.department_id = course.department_id;

Here's another one of my attempts:

(SELECT course.course_title, course.department_id, departments.department_id, departments.department_name WHERE course.course_title = 'Calculus')
-> UNION
-> (SELECT course.course_title, course.department_id, departments.department_id, departments.department_name WHERE course.course_title = 'British Literature I')
-> UNION
-> (SELECT course.course_title, course.department_id, departments.department_id, departments.department_name WHERE course.course_title = 'Studio Art I')
-> FROM departments INNER JOIN course ON departments.department_id = course.department_id;

Any ideas on whether or not this would work? If so, how do I correct my syntax? If not, what's another method?

Thank you!!

Upvotes: 0

Views: 821

Answers (2)

Matt Busche
Matt Busche

Reputation: 14333

You can write your query like below.

SELECT course.course_title, course.department_id, departments.department_id, departments.department_name 
FROM departments 
  INNER JOIN course ON departments.department_id = course.department_id
WHERE course.course_title IN ('Calculus', 'British Literature I','Studio Art I')

Upvotes: 2

Randy
Randy

Reputation: 16677

you should use an IN clause...

like this

WHERE course IN ('Calculus','Physics','Art')

Upvotes: 2

Related Questions