My teacher provided me with this sql code, and I logged in as root into phpmyadmin, added a database called webstore, and then tried to add this code and it's giving me errors. Is there anyone who can tell me what could be causing the errors? I am using a Mac, so I'm not sure if that makes any difference, I can give you a link to dropbox with additional information if necessary.
This is the dropbox link with the code provided (Webstore.sql): https://www.dropbox.com/sh/usfmbeyxqd2q1g5/AADoLFbsz8cL30EC76d60i40a?dl=0
Also, the zip file contains images of the errors I was receiving. PLEASE HELP!!
The SQL statement the error occurs on is
CREATE TABLE Shopping_Cart (
CustID INTEGER NOT NULL,
ProdID INTEGER NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID)
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
The error reads
A comma or closing bracket was expected. (near "CONSTRAINT" at position 153)
Unexpected beginning of statement. (near "CustID" at position 192)
Unrecognised statement type. (near "REFERENCES" at position 206)
Your PRIMARY KEY line needs a comma after it before the CONSTRAINT.
CREATE TABLE Shopping_Cart (
CustID INTEGER NOT NULL,
ProdID INTEGER NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID),
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
Edit
It turns out there were a lot of problems with the SQL. The tables were created in the wrong order and the data types were wrong. Here is a rewritten version that I have tested out:
DROP DATABASE IF EXISTS WebStore;
CREATE DATABASE WebStore;
USE WebStore;
CREATE TABLE Categories (
CatID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
Name VARCHAR(20) NOT NULL,
Descr VARCHAR(120) NOT NULL,
IconURL VARCHAR(64) NOT NULL,
PRIMARY KEY (CatID)
);
CREATE TABLE Products (
ProdID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
Name VARCHAR(20) NOT NULL,
Category INTEGER UNSIGNED,
Descr VARCHAR(120) NOT NULL,
Price FLOAT NOT NULL,
Stock INTEGER UNSIGNED NOT NULL,
IconURL VARCHAR(64) NOT NULL,
PRIMARY KEY (ProdID),
CONSTRAINT FK_Cat FOREIGN KEY FK_Cat (Category)
REFERENCES Categories (CatID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
INSERT INTO Categories VALUES(null,"Laptops","Small computers you can carry","http://localhost/images/laptop.jpg");
SET #laptops := LAST_INSERT_ID();
INSERT INTO Categories VALUES(null,"Desktops","Big computers you cannot carry","http://localhost/images/desktop.jpg");
SET #desktops := LAST_INSERT_ID();
INSERT INTO Categories VALUES(null,"Tablets"," Flat things you lose frequently","http://localhost/images/tablet.jpg");
SET #tablets := LAST_INSERT_ID();
INSERT INTO Products VALUES(null,"DULL 1200",#desktops,"A big dull machine",1290.99,23,"http://localhost/images/dull1200.jpg");
INSERT INTO Products VALUES(null,"8P Totalo",#desktops,"Almost as big as the DULL",990.99,2,"http://localhost/images/8ptotalo.jpg");
INSERT INTO Products VALUES(null,"LaNuveau Bingster",#desktops,"Comes in blue and red",690.99,12,"http://localhost/images/lanuveaubingster.jpg");
INSERT INTO Products VALUES(null,"DULL 122",#laptops,"Small, portable and useless",422.99,4,"http://localhost/images/dull122.jpg");
INSERT INTO Products VALUES(null,"8P Tootsie",#laptops,"Sticky and too heavy",559.99,12,"http://localhost/images/8ptootsie.jpg");
INSERT INTO Products VALUES(null,"LaNuveau Shoobie XT",#laptops,"Weighs a ton but looks sharp",1690.99,122,"http://localhost/images/lanuveaushoobiext.jpg");
INSERT INTO Products VALUES(null,"Motor Roller 12",#tablets,"The only one with a oval screen",422.99,4,"http://localhost/images/mr12.jpg");
INSERT INTO Products VALUES(null,"SamSings OffKey",#tablets,"Needs duct tape to run",559.99,2,"http://localhost/images/samsingsOK.jpg");
INSERT INTO Products VALUES(null,"jPet 12",#tablets,"The first that kinda sorta works",16290.99,722,"http://localhost/images/jpet12.jpg");
CREATE TABLE Customers (
CustID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
FirstName VARCHAR(40) NOT NULL,
LastName VARCHAR(40) NOT NULL,
Address VARCHAR(60) NOT NULL,
City VARCHAR(40) NOT NULL,
State VARCHAR(20) NOT NULL,
Zip VARCHAR(5) NOT NULL,
PRIMARY KEY (CustID)
);
INSERT INTO Customers VALUES(null,"Gerald","Bostock","1234 TAAB Drive","St. Cleve","FL","12345");
INSERT INTO Customers VALUES(null,"Suzy","Creamcheese","8722 Zappa Road","Paris","TX","75460");
CREATE TABLE Shopping_Cart (
CustID INTEGER UNSIGNED NOT NULL,
ProdID INTEGER UNSIGNED NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID),
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
INSERT INTO Shopping_Cart VALUES("1","4","2");
INSERT INTO Shopping_Cart VALUES("1","9","1");
Related
I am having trouble figuring out the best design for my many-to-many relationship in my database. My project allows users to create what we are calling log alarms. A log alarm will check if a given log meets certain criteria and, if so, it will send a message to an AWS SNS topic. What I want to do is relate log alarms to AWS SNS topics. I also want to relate which user assigned that log alarm to that AWS SNS topic.
I have a table class XRefUserLogAlarmSNSTopic. It has three foreign keys. The goal of this table is to relate which SNS topics are related to what log alarms and to indicate which user made the relation. This seems rather messy to me and I get all sorts of errors when I try to create new log alarms or join tables in Spring JPA. My question is, is there are better database structure for what I am trying to achieve
UserId INT NOT NULL AUTO_INCREMENT,
Username VARCHAR(50) NOT NULL,
Password TEXT NOT NULL,
Email VARCHAR(255) NOT NULL,
Dashboard LONGTEXT NOT NULL,
PRIMARY KEY (UserId),
UNIQUE (Username),
UNIQUE (Email)
);
CREATE TABLE SNSTopics (
SNSTopicId INT NOT NULL AUTO_INCREMENT,
TopicName VARCHAR(50) NOT NULL,
TopicArn VARCHAR(255) NOT NULL,
PRIMARY KEY (SNSTopicId),
UNIQUE (TopicName),
UNIQUE (TopicArn)
);
CREATE TABLE LogGroups (
LogGroupId INT NOT NULL AUTO_INCREMENT,
Name VARCHAR(255) NOT NULL,
PRIMARY KEY (LogGroupId),
UNIQUE (Name)
);
CREATE TABLE Keywords (
KeywordId INT NOT NULL AUTO_INCREMENT,
Word VARCHAR(70),
PRIMARY KEY (KeywordId),
UNIQUE (Word)
);
CREATE TABLE LogAlarms (
LogAlarmId INT NOT NULL AUTO_INCREMENT,
LogLevel VARCHAR(5) NOT NULL CHECK (LogLevel IN ('TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR')),
Comparison VARCHAR(2) CHECK (Comparison IN ('==', '<', '<=', '>', '>=')),
AlarmName VARCHAR(255) NOT NULL,
KeywordRelationship CHAR(3) CHECK (KeywordRelationship IN ('ANY', 'ALL', NULL)),
PRIMARY KEY (LogAlarmId),
UNIQUE (AlarmName)
);
CREATE TABLE MetricAlarms (
MetricAlarmId INT NOT NULL AUTO_INCREMENT,
AlarmArn VARCHAR(100) NOT NULL,
PRIMARY KEY (MetricAlarmId),
UNIQUE (AlarmArn)
);
CREATE TABLE XRefUserMetricAlarm (
UserMetricAlarmId INT NOT NULL AUTO_INCREMENT,
UserId INT NOT NULL,
MetricAlarmId INT NOT NULL,
PRIMARY KEY (UserMetricAlarmId),
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE,
FOREIGN KEY (MetricAlarmId) REFERENCES MetricAlarms(MetricAlarmId) ON DELETE CASCADE,
UNIQUE (UserId, MetricAlarmId)
);
CREATE TABLE XRefLogAlarmLogGroup (
LogAlarmLogGroupId INT NOT NULL AUTO_INCREMENT,
LogAlarmId INT NOT NULL,
LogGroupId INT NOT NULL,
PRIMARY KEY (LogAlarmLogGroupId),
FOREIGN KEY (LogAlarmId) REFERENCES LogAlarms(LogAlarmId) ON DELETE CASCADE,
FOREIGN KEY (LogGroupId) REFERENCES LogGroups(LogGroupId) ON DELETE CASCADE,
UNIQUE (LogAlarmId, LogGroupId)
);
CREATE TABLE XRefLogAlarmKeyword (
LogAlarmKeywordId INT NOT NULL AUTO_INCREMENT,
LogAlarmId INT NOT NULL,
KeywordId INT NOT NULL,
PRIMARY KEY (LogAlarmKeywordId),
FOREIGN KEY (LogAlarmId) REFERENCES LogAlarms(LogAlarmId) ON DELETE CASCADE,
FOREIGN KEY (KeywordId) REFERENCES Keywords(KeywordId) ON DELETE CASCADE,
UNIQUE (LogAlarmId, KeywordId)
);
CREATE TABLE XRefUserLogAlarmSNSTopic (
UserLogAlarmSNSTopicId INT NOT NULL AUTO_INCREMENT,
LogAlarmId INT NOT NULL,
SNSTopicId INT NOT NULL,
UserId INT NOT NULL,
PRIMARY KEY (UserLogAlarmSNSTopicId),
FOREIGN KEY (LogAlarmId) REFERENCES LogAlarms(LogAlarmId) ON DELETE CASCADE,
FOREIGN KEY (SNSTopicId) REFERENCES SNSTopics(SNSTopicId) ON DELETE CASCADE,
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE,
UNIQUE (LogAlarmId, SNSTopicId, UserId)
);```
To match your description, your XRefUserLogAlarmSNSTopic is not correct.
You do not actually want to link three entities, just two: you want to relate log alarms to AWS SNS topics (which are the two values that identify that relationship), and then add a user as an attribute to that relation. Although in this case this specific attribute refers to another entity, it is logically not fundamentally different than e.g. a timestamp that stores when that relationsship was created (by that user).
The difference to your current table is the primary key/unique key: your current table allows you to add a relationship between an alarm and a topic several times if different users add them, as only (alarm, topic, user) needs to be unique, instead of (alarm, topic) being unique, and user being an attribute to that relation.
I would also consider if you want an ON DELETE CASCADE for the UserId column. While cascading for LogAlarmId and SNSTopicId makes sense, it's not obvious that you need to remove all relations when you delete the user that created them (although it of course depends on your requirements). It may be better to just set them to null. So I would propose a table like
CREATE TABLE XRefLogAlarmSNSTopic ( -- user not part of table name
LogAlarmSNSTopicId INT NOT NULL AUTO_INCREMENT,
LogAlarmId INT NOT NULL,
SNSTopicId INT NOT NULL,
UserId INT NULL, -- null
PRIMARY KEY (UserLogAlarmSNSTopicId),
FOREIGN KEY (LogAlarmId) REFERENCES LogAlarms(LogAlarmId) ON DELETE CASCADE,
FOREIGN KEY (SNSTopicId) REFERENCES SNSTopics(SNSTopicId) ON DELETE CASCADE,
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE SET NULL, -- set null
UNIQUE (LogAlarmId, SNSTopicId) -- user not part of primary key candidate
)
It is obviously also possible that you want that 3-way-relationship, e.g. each user creates their own alarm-topic-relations, in which case your table would be correct, just your description would not be precise enough.
Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
I am trying to create three tables such as associate, manager and attendance. The attendance table should be having employee and manager details from the other two table which should enable marking the attendance. I created this SQL script. I'm not sure where I am making mistake.
CREATE TABLE associate (
id INT NOT NULL,
idmanager INT NOT NULL,
emp_id DATE NOT NULL,
emp_name VARCHAR(25) NOT NULL,
FOREIGN KEY (id) REFERENCES attendance (associate_id) ON DELETE CASCADE,
FOREIGN KEY (idmanager) REFERENCES attendance (manager_idmanager) ON DELETE CASCADE,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE manager (
id INT NOT NULL,
mgr_usr_id VARCHAR(15) NOT NULL,
mgr_name VARCHAR(25) NOT null,
KEY (id),
KEY (mgr_usr_id),
FOREIGN KEY (id) REFERENCES associate (idmanager) ON DELETE CASCADE,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INT NOT NULL,
manager_idmanager INT NOT NULL,
associate_id INT NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno)
) ENGINE=INNODB;
Screenshot
It's an issue of ordering. For example, the first statement executed is
CREATE TABLE associate (
which references attendance. However, the attendance table has not yet been created. Switch the order so that any tables that reference other tables come last.
Alternatively, don't put the FOREIGN KEY constraints in the CREATE statements, but them at the end of your script with ALTER TABLE statements. Consider:
CREATE TABLE associate (
id INT NOT NULL,
idmanager INT NOT NULL,
emp_id DATE NOT NULL,
emp_name VARCHAR(25) NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INT NOT NULL,
manager_idmanager INT NOT NULL,
associate_id INT NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno)
) ENGINE=INNODB;
ALTER TABLE associate ADD FOREIGN KEY (id) REFERENCES associate(id) ON DELETE CASCADE;
Edit
The above is just syntax. To model the requested problem consider orthogonality of information. You might also see/hear "normalization." The basic concept is this: have only one copy of your information. The schema should have a single point of authority for all data. For example, if a user has a birthdate, make sure you don't have an ancillary column that also stores their birthday; it's superfluous information and can lead to data errors.
In this case, what is the relationship? What must come first for the other to exist? Can an attendance be had without a manager? How about a manager without attendance? The former makes no sense. In this case then, I would actually use a third table, to form a hierarchy.
Then, consider that maybe roles change in a company. It would not behoove the DB architect to hard code roles as tables. Consider:
CREATE TABLE employee (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(25) NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE role (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
description VARCHAR(254) NOT NULL,
PRIMARY KEY( id ),
UNIQUE( name )
) ENGINE=INNODB;
INSERT INTO role (name, description) VALUES
('associate', 'An associate is a ...'),
('manager', 'A manager follows ...');
CREATE TABLE employee_role (
employee_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
PRIMARY KEY (employee_id, role_id),
FOREIGN KEY (idemployee_id) REFERENCES employee_id (id) ON DELETE CASCADE,
FOREIGN KEY (role_id) REFERENCES role (id) ON DELETE CASCADE
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INTEGER NOT NULL,
employee_id INTEGER NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno),
FOREIGN KEY (idemployee_id) REFERENCES employee_id (id) ON DELETE CASCADE
) ENGINE=INNODB;
From this schema, the attendance needs only one foreign key because everyone is an employee. Employee's can have multiple roles, and they can change. Further, role definitions can change without needing to resort to costly DDL statements (data definition layer changes, like ALTER TABLE), and can be modified with simple DML (data manipulation layer changes, like UPDATE TABLE). The former involves rewriting all entries in the tables, and changing schemas, while the latter involves changing individual entries.
Structure:
Table A)
CREATE TABLE Item (
Id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Unique id of an item',
`By` VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (Id),
CONSTRAINT FK_Item_User_Name FOREIGN KEY (`By`)
REFERENCES User(Name) ON DELETE NO ACTION ON UPDATE CASCADE
)
Table B)
CREATE TABLE ItemName (
Item_Id INT(11) UNSIGNED NOT NULL COMMENT 'Item id this name is referencing',
Language VARCHAR(5) NOT NULL COMMENT 'language code by ISO 639-2/T',
Translation VARCHAR(50) NOT NULL COMMENT 'Item name for given language',
PRIMARY KEY (Item_Id, Language),
CONSTRAINT FK_ItemName_Item_Id FOREIGN KEY (Item_Id)
REFERENCES Item(Id) ON DELETE CASCADE ON UPDATE CASCADE
)
Table C)
CREATE TABLE User (
Name VARCHAR(50) NOT NULL,
Password VARCHAR(50) NOT NULL,
Salt VARCHAR(255) NOT NULL,
Blocked TINYINT(1) DEFAULT 0,
PRIMARY KEY (Name),
UNIQUE INDEX UK_User_Name (Name)
)
Question:
Now I want to insert a new item. Let's say the user provides us with:
Translation
Language code
Username
What i got so far:
I was thinking of puting it in a transaction and inserting into each table after eachother. But then i'm stuck on how do i know what Item.Id to use in the ItemName.Item_Id field since the Item table will AI a new Id for the insert.
I could get the last Item.Id, but then it might be pointing to another item if multiple users were to be inserting a new item simulaneuosly.
ps. Engine=InnoDB
BEGIN;
INSERT into one table;
get the last_insert_id() -- there are many ways to do this, depending on the API
INSERT into next table...
... ;
COMMIT;
Do the inserts in the order that avoids violating your FOREIGN KEYs.
I would like some help with an SQL query that I am struggling with, Ive got 90% of what I need it to do done its just the last bit that I'm having a little issue with.
Database Design
I have the following database Schema
CREATE TABLE IF NOT EXISTS EMPLOYEES(
ID INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR(255) NOT NULL,
LAST_NAME VARCHAR(255) NOT NULL,
SEX CHAR(1) NOT NULL,
COST INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS SKILLS(
ID INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
SKILL VARCHAR(300) NOT NULL
);
CREATE TABLE IF NOT EXISTS EMPLOYEE_SKILLS(
EMPLOYEE_ID INTEGER NOT NULL,
SKILL_ID INTEGER NOT NULL,
PROFICIENCY SET('1','2','3','4') NOT NULL,
PRIMARY KEY(EMPLOYEE_ID,SKILL_ID),
UNIQUE INDEX(SKILL_ID,EMPLOYEE_ID),
FOREIGN KEY (EMPLOYEE_ID) REFERENCES EMPLOYEES(ID) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (SKILL_ID) REFERENCES SKILLS(ID) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS PROJECTS(
ID INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
NAME VARCHAR(300) NOT NULL,
LOCATION VARCHAR(255) DEFAULT NULL,
INCOME INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS TASKS(
ID INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
NAME VARCHAR(300) NOT NULL,
PROJECT_ID INTEGER NOT NULL,
DATE_FROM DATE NOT NULL,
DATE_TO DATE NOT NULL,
COMPLETED BOOLEAN DEFAULT 0,
FOREIGN KEY (PROJECT_ID) REFERENCES PROJECTS(ID) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS TASK_SKILLS(
TASK_ID INTEGER NOT NULL,
SKILL_ID INTEGER NOT NULL,
PROFICIENCY_REQUIRED SET('1','2','3','4') NOT NULL,
PRIMARY KEY(TASK_ID,SKILL_ID),
UNIQUE INDEX(SKILL_ID,TASK_ID),
FOREIGN KEY (TASK_ID) REFERENCES TASKS(ID) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (SKILL_ID) REFERENCES SKILLS(ID) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS ASSIGNED_TO(
EMPLOYEE_ID INTEGER NOT NULL,
TASK_ID INTEGER NOT NULL,
DATE_ASSIGNED DATETIME NOT NULL,
PRIMARY KEY(EMPLOYEE_ID,TASK_ID),
UNIQUE INDEX(TASK_ID,EMPLOYEE_ID),
FOREIGN KEY (EMPLOYEE_ID) REFERENCES EMPLOYEES(ID) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (TASK_ID) REFERENCES TASKS(ID) ON UPDATE CASCADE ON DELETE CASCADE
);
Query
So the query that I would like to create would be to return every EMPLOYEE within the database along with their SKILLS and the PROFICIENCY of their skill. This was the part of the query where I had no trouble with and I have the following query:
SELECT EMPLOYEES.ID, CONCAT_WS(' ',EMPLOYEES.FIRST_NAME,EMPLOYEES.LAST_NAME) AS NAME, GROUP_CONCAT(SKILLS.SKILL),EMPLOYEES.COST,GROUP_CONCAT(EMPLOYEE_SKILLS.PROFICIENCY)
FROM EMPLOYEE_SKILLS
JOIN EMPLOYEES ON EMPLOYEE_SKILLS.EMPLOYEE_ID = EMPLOYEES.ID
JOIN SKILLS ON EMPLOYEE_SKILLS.SKILL_ID = SKILLS.ID
GROUP BY EMPLOYEES.ID
The above query gives me the majority of what I want, where it returns every employee within the database and their associated skill and the level that they know it at.
The thing that I am struggling with now is that I would also like to join up this query to also look into the ASSIGNED_TO table of the database as well, where I would like to find all the employees within the organisation (assigned to a task or not) and return the TASK ID that they have been assigned and the start and end date of said task.
Ive tried simply adding another join to the ASSIGNED_TOtable within the above query but it doesn't give me the desired output. I'm suspecting because I am grouping by the employee id. Would I need to use something like two queries to get what I want, for example and inner select and an outer select and do an inner join between them? Not really sure what the approach would be for this query.
Sorry for the long post and any help will be much appreciated.
Thanks.