I have an employee and a task table like this:
Table employees
id not null primary key,
name
Table Tasks
id primary key,
author id not null references employees (id),
assigneeid references employees (id)
I am trying to write a query that would return task id, author name, and assignee name and if there is no assignee name then I want to return null. FYI, this is not a homework question but I'm learning backend development and I need to brush up my sql skills.
UPDATE:
Here is the expected output
-- Expected output (in any order):
-- id author assignee
-- ----------------------
-- 1 Richard
-- 2 Lily Richard
You are looking for two left joins:
select t.*, eau.name as author, eas.name as assignee
from tasks t left join
employees eau
on eau.id = t.author_id left join
employees eas
on eas.id = t.assignee_id;
Related
Just started learning SQL and need help on the Feb 1, 2020 part.
The database has three tables for tracking horse-riding lessons:
Horse with columns:
ID - primary key
RegisteredName
Breed
Height
BirthDate
Student with columns:
ID - primary key
FirstName
LastName
Street
City
State
Zip
Phone
EmailAddress
Lesson Schedule with columns:
HorseID - partial primary key, foreign key references Horse(ID)
StudentID - foreign key references Student(ID)
LessonDateTime - partial primary key
Write a SELECT statement to create a lesson schedule for Feb 1, 2020 with the lesson date/time, student's first and last names, and the horse's registered name. Order the results in ascending order by lesson date/time, then by the horse's registered name. Make sure unassigned lesson times (student ID is NULL) appear in the results.
Hint: Perform a join on the LessonSchedule, Student, and Horse tables, matching the student IDs and horse IDs.
This is what I have; not sure of the correct way to go about it. I've tried using WHERE and AND but get an error or only all NULL first/last names in the table.
SELECT LessonDateTime, FirstName, LastName, RegisteredName
FROM LessonSchedule
LEFT JOIN Student ON LessonSchedule.StudentID = Student.ID
INNER JOIN Horse ON LessonSchedule.HorseID = Horse.ID
ORDER BY LessonDateTime, RegisteredName;
Please try this.
I think it will work.
SELECT LessonDateTime, FirstName, LastName, RegisteredName
FROM LessonSchedule
LEFT JOIN Student ON LessonSchedule.StudentID = Student.ID
INNER JOIN Horse ON LessonSchedule.HorseID = Horse.ID
WHERE LessonDateTime = '2020-02-01'
ORDER BY LessonDateTime, RegisteredName;
Given the following two relational schemas, the EMPLOYEE relational schema records the employee number (ssn), age (age) and the department (dno), the primary key is ssn, and the DEPARTMENT relational schema records the department number (dnum ) and name (dname), The primary key is dnum, in which the foreign key "dno" of EMPLOYEE refers to the primary key "dnum" of DEPARTMENT,
please use SQL GROUP BY to write the query ''For each department that has more than two employees, retrieve the department name and the number of its employees who each is more than twenty-five years old)”.
Thank you guys
You can use as approach. It's not exactly your tables but you can easy match it tot your structure:
SELECT DEPARTMENT_NAME
FROM DEPARTMENTS D
JOIN EMPLOYEES E USING (DEPARTMENT_ID)
GROUP BY DEPARTMENT_ID, DEPARTMENT_NAME
HAVING COUNT(EMPLOYEE_ID) > 2
;
format sql online
SELECT d.dname, count(e.ssn) as cnt
FROM Employee e JOIN department d
on e.dno = d.dnum
WHERE e.age> = 25
Group BY e.dname
HAVING COUNT(ssn) >= 2;
I have an application based on 4 MySQL tables:
persons
------------
id -- Primary key, unique
name
entity_id -- foreign key => entities
entities
------------
id -- Primary key, unique
name
company_id -- foreign key => companies
companies
------------
id -- Primary key, unique
name
persons_linked_companies -- join table : persons <=> companies
--------------------------
id -- Primary key, unique
persons_id -- foreign key => persons
companies_id -- foreign key => companies
Each "person" belong to an "entity"
Each "entity" belong to a "company"
A "person" can only have one "entity"
An "entity" can only have one "company"
A "person" can be linked to one or more third parties (meaning other companies). For this there is a join table called "persons_linked_companies"
A person can have multiple linked companies, but a person shouldn't be linked to his own company
I can't figure out what kind of subquery/join I should issue to get the following data:
I need to select entries in the join table "persons_linked_companies" to get all persons whose linked company is the same has the company they belong to (because of bullet point 6).
Pseudo code below:
select id from persons_linked_companies where companies_id = (select id from companies where persons.entity.company_id = persons_linked_companies.companies_id)
Besides using aliases. you can join all tables
But this would only yield a result, if you entered such a row in the table persons_linked_companies, which should be not be done by your rule 6
SELECT
id
FROM
persons_linked_companies pcl
WHERE
companies_id = (SELECT
c.id
FROM
companies c
INNER JOIN entities e ON e.company_id = c.id
INNER JOIN persons p ON p.entity_id = e.id
WHERE
p.id = pcl.persons_id)
I am using MySQL Workbench, and I have the following question:
Using the employees data, create select queries that will provide the following information:
Show a list of employees and what department they are in
Columns: Employee Name, Department Name
I have two statements which provide the exact same return, but it's 1000 rows! Am I doing this "join" properly?
SELECT
departments.dept_name, employees.last_name, employees.first_name
FROM
departments, employees
WHERE
departments.dept_name = employees.departments.dept_name;
and
SELECT
dept_name, last_name, first_name
FROM
departments
INNER JOIN
employees
ON
departments.dept_name = employees.departments.dept_name;
Tables employees and departments are always many to many. Therefore, we need input table between them, which has columns id_emp and id_dep or more often 4 column, id_emp, id_dep, from, to. After that, your question is clear and we can speak about.
Example:
Tables:
employees emp_dep departments
id_emp first_name id id_emp id_dep id_dep name
1 John 1 1 1 1 Finacial
2 Elsa 2 2 2 2 Human res
Note: id_emp & id_dep in table emp_dep can't be together primary key beacause every employee can work many times again in same department.
Query on 3 table:
SELECT e.first_name,
d.name
FROM (employees e
INNER JOIN emp_dep ed ON e.id_emp = ed.id_emp)
INNER JOIN departments d ON ed.id_dep = d.id_dep;
Output:
first_name name
John Financial
Elsa Human res
SQL for create this database and table:
CREATE DATABASE employees_dep;
CREATE TABLE employees (id_emp INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(10));
CREATE TABLE departments (id_dep INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(10));
CREATE TABLE emp_dep (id int AUTO_INCREMENT PRIMARY KEY, id_emp INT, id_dep INT);
Both are correct, but the second is better.
Both are same. However second one would be faster given large volume of data, but won't matter on small sized tables.
First and foremost, this is part of an assignment, but I'm trying to get more clarification on how the count() function works when querying a db.
The question is: List the name, SSN and the number of courses the student has taken (courses with the same CourseNumber taken in different quarters are counted as different courses).
I've been querying using this:
SELECT S.Name, S.SSN, COUNT(*)
FROM Student S, Enrollment E
WHERE S.SSN = E.SSN
GROUP BY S.SSN
which seems to return the correct answer, but I'm not sure why. As a result, I can't seem to get the next questions (assuming courses with the same CourseNumber taken in different quarters are considered as one course) correct.
Here are the create table commands so you can see which table holds what info:
CREATE TABLE Student(
SSN INT(9),
Name VARCHAR(20),
Major VARCHAR(30),
PRIMARY KEY (SSN)
);
CREATE TABLE Course(
CourseNumber INT(5),
PrerequisiteCourseNumber INT(10),
CourseTitle VARCHAR(10),
NumberUnits INT(2),
PRIMARY KEY (CourseNumber)
);
CREATE TABLE Section(
CourseNumber INT(5),
Quarter VARCHAR(10),
RoomNumber INT(5),
DayTime VARCHAR(20),
PRIMARY KEY (CourseNumber,Quarter),
FOREIGN KEY (CourseNumber) REFERENCES Course(CourseNumber)
);
CREATE TABLE Enrollment(
SSN INT(9),
CourseNumber INT(5),
Quarter VARCHAR(10),
Grade VARCHAR(1),
PRIMARY KEY (SSN,CourseNumber,Quarter),
FOREIGN KEY (SSN) REFERENCES Student(SSN),
FOREIGN KEY (CourseNumber) REFERENCES Course(CourseNumber),
FOREIGN KEY (Quarter) REFERENCES Section(Quarter)
);
Any pointers?
what you are doing is using old join syntax (pre ansi syntax) where you do a cross join of tables and use the where to turn it into a join. an equivalent query would be this.
SELECT S.Name, S.SSN, COUNT(*)
FROM Student S
JOIN Enrollment E ON S.SSN = E.SSN
GROUP BY S.SSN
Now to answer your question about what the count is doing and stuff..
COUNT() returns a count of every row that is returned.
GROUP BY groups all of the records by a common ground aka your SSN field. so if a student has 5 SSN rows in the table then his count will be 5.
Now for the part you are looking for with course numbers.. you need to JOIN those tables on appropriate fields and add a field to your group by for each quarter
aka add to the previous code..
WHERE E.quarter = whatever_quarter_you_want
you can add more to this query if you need to. but add data to your question if you want a more full answer.
Your current query is:-
SELECT S.Name, S.SSN, COUNT(*)
FROM Student S
INNER JOIN Enrollment E
ON S.SSN = E.SSN
GROUP BY S.SSN
What this is doing is joining student to enrollment, so giving multiple rows for each student, one for each course / quarter they are enrolled on. It is then grouped by SSN (student number?) to count up the number of course / quarters they are enrolled on. You should really group by S.Name as well (while MySQL won't object, most flavours of SQL would).
Note that COUNT(*) counts the number of rows. You could use COUNT(E.CourseNumber) which would count the number of rows where course number is not null. Not really useful here, but can be useful with LEFT OUTER JOINs. You can also use COUNT(DISTINCT CourseNumber) to count the number of unique non null course numbers for the student.
A LEFT OUTER JOIN might also be better as this would enable you to return 0 as the counts for students who exist but who are not enrolled in any courses:-
SELECT S.Name, S.SSN, COUNT(DISTINCT E.CourseNumber)
FROM Student S
LEFT OUTER JOIN Enrollment E
ON S.SSN = E.SSN
GROUP BY S.Name, S.SSN
SELECT S.Name, S.SSN, COUNT(*)
FROM Student S, Enrollment E, Section Sec, Course C
WHERE S.SSN = E.SSN AND E.CourseNumber = Sec.CourseNumber
AND Sec.CourseNumber = C.CourseNumber AND Sec.Quarter like E.Quarter
GROUP BY S.Name, S.SSN