Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query for distinct professors and courses

Tags:

sql

mysql

schema

The question is stated as there is a database on professors, departments, courses and schedules. Need to write a query that returns the names of all the professors and their respective courses. Each row must contain the name of the professor followed by the name of the course that the professor teaches. There must be no duplicates in terms of the rows.

The schema I have, in terms of the table name and the fields:

PROFESSOR: ID, NAME, DEPARTMENT_ID, SALARY
DEPARTMENT: ID, NAME
COURSE: ID, NAME, DEPARTMENT_ID, CREDITS
SCHEDULE: PROFESSOR_ID, COURSE_ID, SEMESTER, YEAR

The code I have right now:

SELECT DISTINCT p.Name AND c.NAME
FROM Prodessor p, Course c, Schedule S

WHERE
    p.DEPARTMENT_ID = c.DEPARTMENT_ID
    AND
    p.ID = s.PROFESSOR_ID
    AND
    c.ID = c.COURSE_ID

The result I get is a list of all professors, but there aren't multiple courses, just a single one. What's going wrong here? It also mentioned that PROFESSOR.ID is foreign to COURSE.PROFESSOR_ID, so p.ID = s.PROFESSOR_ID is valid

like image 465
SDG Avatar asked Oct 23 '19 01:10

SDG


People also ask

What does <> operator mean in SQL?

An operator is a reserved word or a character that is used to query our database in a SQL expression. To query a database using operators, we use a WHERE clause. Operators are necessary to define a condition in SQL, as they act as a connector between two or more conditions.

Is unique a keyword in SQL?

The UNIQUE keyword in SQL plays the role of a database constraint; it ensures there are no duplicate values stored in a particular column or a set of columns.

How do you select a vowel in SQL?

To check if a name begins ends with a vowel we use the string functions to pick the first and last characters and check if they were matching with vowels using in where the condition of the query. We use the LEFT() and RIGHT() functions of the string in SQL to check the first and last characters.

Is not equal to in SQL?

The SQL Not Equal comparison operator (!=) is used to compare two expressions. For example, 15 !=


2 Answers

I think the below code will solve your requirement

SELECT distinct p.name,c.name
from Professor p 
inner join Schedule s on p.id=s.professor_id
inner join course c on c.id=s.course_id;
like image 169
Abhijit Jadhav Avatar answered Oct 04 '22 16:10

Abhijit Jadhav


Alternatively if we want professors with the names of the courses they teach (or have taught) outside of their department.

select distinct p.name, c.name
FROM professor p
JOIN schedule s on s.professor_id = p.id
JOIN course c on s.course_id = c.id
WHERE c.department_id <> p.department_id;
like image 44
Ajay Jindal Avatar answered Oct 04 '22 15:10

Ajay Jindal