I'm using My SQL (latest version) and I have the following table:
CREATE TABLE COURSES (
IDCOURSE INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR (30) NOT NULL,
HOURS INT,
PRICE FLOAT (10,2) NOT NULL,
ID_PREREQ INT
);
ALTER TABLE COURSES ADD CONSTRAINT FK_PREREQ
FOREIGN KEY (ID_PREREQ) REFERENCES COURSES (IDCOURSE);
What I want do is: select the columns NAME, HOURS, PRICE and ID_PREREQ AS REQUISITES. Whenever ID_PREREQ is NULL, I want to read "NO REQUISITES". If else, then I want to read whatever's in the associated NAME column.
For example:
If this is my table:
IDCOURSE | NAME | HOURS | PRICE | ID_PREREQ |
---|---|---|---|---|
1 | RELATIONAL DB | 20 | 400.00 | NULL |
2 | BUSINESS INTELLIGENCE | 40 | 800.00 | 1 |
3 | ADVANCED DB | 20 | 600.00 | 2 |
4 | PROGRAMMING | 20 | 400.00 | NULL |
I'd like a select to show me this:
NAME | HOURS | PRICE | REQUISITES |
---|---|---|---|
RELATIONAL DB | 20 | 400.00 | NO REQUISITES |
BUSINESS INTELLIGENCE | 40 | 800.00 | RELATIONAL DB |
ADVANCED DB | 20 | 600.00 | BUSINESS INTELLIGENCE |
PROGRAMMING | 20 | 400.00 | NO REQUISITES |
What I've tried so far:
With this solution, I came across two different problems:
1. How to show the NAME related to the correct ID_PREREQ?
I managed to write the following code:
SELECT CASE WHEN ID_PREREQ IS NOT NULL
THEN NAME
ELSE 'NO REQUISITES'
END
FROM COURSES;
But as you can see, I'm merely repeting the name column in the REQUISITES column, instead of getting the associated value I want. I was also unable to give the result column its proper name (REQUISITES).
2. How to select more columns besides the REQUISITES column?
I've tried this:
But for some reason I got a syntax error.
Finally, I also tried the IIF Statement because the syntax seemed easier, but I got an ERROR 1305: FUNCTION does not exist.
I don't understand why is that, considering that I'm using the latest MySQL version and apparently that IIF statement was released in 2012.
Can somebody please help me?
Thank you!