PostgreSQL connecting two tables with 2 common attributes on Query - sql

I have 2 entities; castfilm and staff in my erd that have a common attribute employeeid. Now, I wanted to Query in postgre to show the attributes that are related to the specific person that has an employeeid no. 307 where his fname and lname is David and Kaye respectively.
My erd looks like this: enter image description here
The attributes that I wanted to show are fname, lname, castrole, filmtitle, filmgenre, filmyear, companyname, staffposition, artistname and soundtitle that are related to the film of the employee named David Kaye
Here's my query:
SELECT distinct fname,lname,castrole, filmtitle, filmgenre, filmyear, companyname
FROM employee,
castfilm,
film,
production,
company
WHERE employee.employeeid = 307
AND employee.employeeid = castfilm.employeeid
AND castfilm.filmid = film.filmid
AND production.companyid = company.companyid
AND production.filmid = film.filmid
[output][2]
How do I show the other staffs and casts that are related to the specific movie that David Kaye is on?

You can use EXISTSstatement:
The argument of EXISTS is an arbitrary SELECT statement, or subquery.
The subquery is evaluated to determine whether it returns any rows. If
it returns at least one row, the result of EXISTS is "true"; if the
subquery returns no rows, the result of EXISTS is "false".
In the subquery you should check if for given filmid there exists an employeeid in castfilm. And this employeeid should be 307.
Like this:
SELECT distinct fname,lname,castrole, filmtitle, filmgenre, filmyear, companyname
FROM employee,
castfilm,
film,
production,
company
WHERE employee.employeeid = castfilm.employeeid
AND castfilm.filmid = film.filmid
AND production.companyid = company.companyid
AND production.filmid = film.filmid
AND EXISTS (
SELECT
employeeid
FROM
castfilm
WHERE
filmid = film.filmid AND
employeeid = 307
);
Please, note that film.filmid is used in the subquery.
Furthermore, as #jarlh noted, you could use JOIN syntax, like this:
SELECT
fname,
lname,
castrole,
filmtitle,
filmgenre,
filmyear,
companyname
FROM
employee
JOIN castfilm
ON (employee.employeeid = castfilm.employeeid)
JOIN film
ON (castfilm.filmid = film.filmid)
JOIN production
ON (film.filmid = production.filmid)
JOIN company
ON (production.companyid = company.companyid)
WHERE
EXISTS (
SELECT
employeeid
FROM
castfilm
WHERE
filmid = film.filmid AND
employeeid = 307
);

Related

SELECT and JOIN to return only one row for each employee

I have a user table that stores the employeeId, lastName, firstName, department, hire date and mostRecentLogin.
I have another table that stores the employeeId, emailAddress.
The emailAddress table can have multiple rows for an employee if they have multiple email addresses.
I'm trying to return results that only show one row for each employee. I don't care which email address, just as long as it only picks one.
But all the queries I've tried always return all possible rows.
Here is my most recent attempt:
select *
from EmployeeInfo i
left join EmployeeEmail e ON i.employeeId = e.employeeId
where i.hireDate = 2015
and employeeId IN (
SELECT MIN(employeeId)
FROM EmployeeInfo
GROUP BY employeeId
)
But then again, this returns all possible rows.
Is there a way to get this to work?
Use a sub-query instead of a join:
select *
, (select top 1 E.EmailAddress from EmplyeeEmail E where E.employeeId = I.employeeId)
from EmployeeInfo I
where I.hireDate = 2015;
Note: If you change your mind and decide you do have a preference as to which email address is returned then just add an order by to the sub-query - otherwise it is truly unknown which one you will get.
This should work.
SELECT *
FROM EmployeeInfo
Left JOIN EmployeeEmail
ON EmployeeInfo.employeeId = EmployeeEmail.employeeId
WHERE EmployeeInfo.hireDate = '2015'
GROUP BY EmployeeInfo.employeeId;

SQL query - list of items in one table not in another

I need some help with a SQL query. I have a table of courses and a table that contains user id and course id, denoting courses that user has taken (might not have taken any; no entry in that table for that user id).
I need a query to return the list of courses not taken.
Course Category table
CategoryID
Caegory
Courses table
CourseID
CategoryID
CourseName
...
UserCourse table
UserID
CourseID
you can use not exists
Select *
From Courses c
Where Not Exists (Select 1 From UserCourse uc Where uc.CourseID = c.CourseID)
This will just list the course
select *
from Courses C
Left join CourseCategory cc on
cc.CategoryID = c.CategoryID
where CourseID not in (Select CourseID from UserCourse where UserID = 14)
what i need is for a given user id and course category, what courses within that category have not been taken by this user
(This should have been in the request by the way.)
So:
Select from courses.
Limit to the desired category.
Limit to courses not in the set of courses taken by the user.
The query:
select *
from courses
where categoryid = 123
and courseid not in (select courseid from usercourse where userid = 456);
Another way of writing same query, which will perform faster.
select C.CourseID,C.CategoryID
from Courses C
Left join CourseCategory cc on
cc.CategoryID = c.CategoryID
left join UserCourse uc
on C.CourseID=uc.CourseID
where uc.CourseID is null

How to check if there exist only one record for a certain Id

How to check if there exist only one record for a certain Id
I have two tables called Tbl_Company and Tbl_Employee
I am fetching employees as follows-
SELECT DISTINCT emp.employee_id
FROM Tbl_Company comp
, Tbl_Employee emp
WHERE
emp.company_id = comp.company_id
AND emp.company_id = 1234;
This query returns exactly one value.
How can I make sure that above query returns exacly one value for any comany_id I enter.
I tried using solutions given in This post with no success.
Is there any simpler way to do this.
this would return one row per company
SELECT comp.companyid, max(emp.employee_id) lastEmployeeID
FROM Tbl_Company comp
, Tbl_Employee emp
WHERE
emp.company_id = comp.company_id
AND emp.company_id = 1234
GROUP BY comp.companyid
the following query is simple and flexible. it will return a list of all employees which are alone in their companies (returned with full employee information).
you can check if a defined company has one lonely employee by enable condition about company or you can check if employee is a lonely employee by enabling employee condition.
SELECT emp.*
FROM Tbl_Company comp
/*, Tbl_Employee emp*/
WHERE (emp.company_id , 1) in (select t.company_id, count(t.employee_id) from Tbl_Company t )
--AND emp.company_id = 1111 /*filter conditions on company_id*/
--AND emp.employee_id = 1234/*filter conditions on employee_id*/;
I have solved this by using ans by #davegreen100 in comment
SELECT comp.companyid, count(distinct emp.employee_id),
FROM Tbl_Company comp
, Tbl_Employee emp
WHERE
emp.company_id = comp.company_id
AND emp.company_id = 1234
GROUP BY comp.companyid
This will give me the count of employees per company

What is wrong with this database query?

I have the following tables in a database (i'll only list the important attributes):
Person(ssn,countryofbirth)
Parents(ssn,fatherbirthcountry)
Employment(ssn, companyID)
Company(companyID, name)
My task is this: given fatherbirthcountry as input, output the names of companies where persons work whose countryofbirth match the fatherbirthcountry input.
I pretend that the fatherbirthcountry is Mexico and do this:
SELECT name
FROM Company
WHERE companyid = (SELECT companyid
FROM Employment
WHERE ssn = (SELECT ssn
FROM Person
WHERE countryofbirth = 'Mexico');
but it is giving me an error:
>Scalar subquery is only allowed to return a single row.
am I completely off track? Can anybody please help?
The problem is that your subqueries are returning multiple results, so you have to use where in vs. =.
Change where ssn = to where ssn in, and where companyid = to where companyid in.
try using the IN keyword not '='.
try changing your query to this
SELECT name
FROM Company
WHERE companyid IN (SELECT companyid
FROM Employment
WHERE ssn IN (SELECT ssn
FROM Person
WHERE countryofbirth = 'Mexico');
Use:
SELECT c.name
FROM COMPANY c
JOIN EMPLOYMENT e ON e.companyid = c.companyid
JOIN PERSON p ON p.ssn = e.ssn
AND p.countryofbirth = 'Mexico'
You should use In in the where condition since the (SELECT ssn
FROM Person
WHERE countryofbirth = 'Mexico'); may return multiple ssn values.
SELECT name
FROM Company
WHERE companyid = (SELECT companyid
FROM Employment
WHERE ssn IN (SELECT ssn
FROM Person
WHERE countryofbirth = 'Mexico');
Try using IN instead of =
When you write:
select a from T where a = ( select....)
The sub-query must return a single value. In case if it returns multiple values, you get your error.
To solve this we use the IN operator which allows the sub-query to return a set of value (>=0) and your where condition succeeds if a equals any one of those values.
select a from T where a IN ( select....)
See if this works
SELECT c.Name FROM PERSON p
LEFT JOIN Employment e ON p.ssn=e.ssn
LEFT JOIN Company c ON
e.CompanyID=c.CompanyID WHERE
p.countryofbirth=
The error is due to the fact that the one of the two subqueries are returning multiple rows. I would think it likely that you have multiple people born in Mexico for example.
Select Name
From Companies
Where Exists(
Select 1
From Employment
Join Person
On Person.SSN = Employment.SSN
Join Parents
On Parents.SSN = Person.SSN
Where Parents.FatherBirthCountry = Person.CountryOfBirth
And Parents.FatherBirthCountry = #InputParam
And Employment.CompanyId = Companies.CompanyId
)
Ideally use the answer from OMG Ponies using JOINs.
But if you do not like JOINs for whatever reason, then TOP 1 should do the trick for you:
SELECT name
FROM Company
WHERE companyid =(SELECT TOP 1 companyid
FROM Employment
WHERE ssn = ( SELECT TOP 1 ssn
FROM Person
WHERE countryofbirth = 'Mexico');

How to join 2 tables based on a like in mysql

I have 2 tables Employee and Company_Employee.
Employee:
ID, FirstName
Company_Employee:
ID, Company_ID, Employee_ID
I want to do a search by First Name. I was thinking my query would look like:
select FirstName, ID from Employee where FirstName LIKE '%John%' and ID in (select id from Company_Employee)
This query returns no rows. Does anyone know how I can get the rows with a like by FirstName with these 2 tables?
Thanks!
Your query compares a company_employee.id with an employee.id. It should probably compare employee.id with company_employee.employee_id.
You can rewrite the query more clearly with a join:
select *
from employee e
join company_employee ce
on e.id = ce.Employee_ID
where e.FirstName like '%John%'
Something like this
SELECT
*
FROM
Employee e
INNER JOIN Company_Employee ce JOIN ON e.Id = ce.Id)
WHERE
FirstName LIKE '%JOHN%'