SQL JOIN ON issue with aliases or not using aliases - sql

I have three tables called Hours, Projects and Clients. I'm somewhat experienced with SQL statements and can't seem to get my head around why this isn't working.
Projects and Hours tables both share a foreign key called projectid
and Projects and Clients both share a foreign key called clientid.
Here's my query so far:
SELECT hoursworked.h, projectname.p, description.p, archive.p, clientname.c
FROM hours AS h, projects AS p, clients AS c
JOIN h
ON projectid.h = projectid.p
JOIN p
ON clientid.p = clientid.c
WHERE archive.p = 0;
I seem to be getting an error called "#1066 - Not unique table/alias: 'h' "
Not sure where I am going wrong here. Any help would be great.
Thanks in advance!

You are mixing implicit joins and explicit joins. A simple rule: don't use commas in from clauses.
SELECT h.hoursworked, p.projectname, p.description, p.archive, c.clientname
FROM hours h join
projects p
on h.projectid = p.projectid join
clients c
ON p.clientid = c.clientid
WHERE p.archive = 0;
In addition, the syntax for using aliases is <table alias>.<column alias>, not the other way around.

You are using your aliases backwards. You need to use H.HoursWorked, rather than HoursWorked.H, etc. Your JOIN is also incorrect.
Try the following:
SELECT h.hoursworked, p.projectname, p.description, p.archive, c.clientname
FROM hours AS h
JOIN projects AS p ON h.projectid = p.projectid
JOIN clients AS c ON p.clientid = c.clientid
WHERE p.archive = 0;

You need to prepend the table name to the field/column, not put it at the end, and usually you would use AS for field/column aliases, not for table aliases. Also, I would name the tables in the JOINs, not separated by commas in the FROM statement. This is how it should look:
SELECT
h.hoursworked,
p.projectname,
p.description,
p.archive,
c.clientname
FROM hours h
JOIN projects p
ON h.projectid = p.projectid
JOIN clients c
ON p.clientid = c.clientid
WHERE p.archive = 0;

Related

To create a view using 5 tables with all columns of all tables

I have to create a view that joins together all of the columns in the CUSTOMERS, ORDERS, ORDERDETAILS, EMPLOYEES, PAYMENTS and PRODUCTS tables.
the schema for the table is below
I tried the following query, though I am at a loss how to solve the above question :
create view orders_view AS
select *
from sys.customers c
left JOIN EMPLOYEES e
on c.SALESREPEMPLOYEENUMBER = e.EMPLOYEENUMBER
left join sys.orders o
on c.CUSTOMER NUMBER = o.CUSTOMERNUMBER
left join sys.orderdetails od
on o.ORDERNUMBER = od.ORDERNUMBER
left join sys.products p
on od.PRODUCTCODE = p.PRODUCTCODE
left join sys.PAYMENTS py
on c.CUSTOMERNUMBER = py.customernumber
I am a newbie with SQL and databases, so any help is appreciated.
Here are some observations on things going wrong:
You have curly braces that are not necessary (perhaps this is a typo in the question).
You are selecting *, but have duplicate column names (such as productcode), which prevents the view from being created. Best practice: list all the columns explicitly in the view.
You have c.CUSTOMER NUMBER = o.CUSTOMERNUMBER. The space is probably a typo. If not, change the name so the space is not part of the name. Best practice: Use identifiers that do not have to be escaped.
I am not aware of a sys.customers table. The sys schema should only be used for internal Oracle objects. (Here is one source.)
thank you for all the inputs. they helped me a lot in figuring out the answer.
Following is the query for the question asked above.it gave me a view with columns from all tables.
create or replace view overall AS
select c.*,
e.LASTNAME,
e.FIRSTNAME,
e.EXTENSION,
e.EMAIL,
e.OFFICECODE,
e.REPORTSTO,
e.JOBTITLE,
o.ORDERNUMBER,
o.ORDERDATE,
o.REQUIREDDATE,
o.SHIPPEDDATE,
o.STATUS,
o.COMMENTS,
od.PRODUCTCODE,
od.QUANTITYORDERED,
od.PRICEEACH,
od.ORDERLINENUMBER,
p.PRODUCTNAME,
p.PRODUCTLINE,
p.PRODUCTSCALE,
p.PRODUCTVENDOR,
p.PRODUCTDESCRIPTION,
p.QUANTITYINSTOCK,
p.BUYPRICE,
p.MSRP,
py.CHECKNUMBER,
py.PAYMENTDATE,
py.AMOUNT
from sys.customers c
left JOIN EMPLOYEES e
on c.SALESREPEMPLOYEENUMBER = e.EMPLOYEENUMBER
left join sys.orders o
on c.CUSTOMERNUMBER = o.CUSTOMERNUMBER
left join sys.orderdetails od
on o.ORDERNUMBER = od.ORDERNUMBER
left join sys.products p
on od.PRODUCTCODE = p.PRODUCTCODE
left join sys.PAYMENTS py
on c.CUSTOMERNUMBER = py.customernumber
;
Your query looks alright, but I don't think it will let you create a view if more than one column has the same name.
Since there are duplicates, e.g. CITY, I think the only way around it is to name all the columns and give unique names for duplicate columns.

SQL SELECT QUERY RELATION TABLES

I'm a little lost with sql. I'm trying to get values of referenced tables, and i have to go throught 6 tables but i'm not getting any result. This is my code:
SELECT v.VEHICLEPLATE, p.NAME
FROM ITV i, VEHICLE v, BUYS b, PERSON p, CENTER c, WORKER w
WHERE
w.NICK = 'PEPE' AND
c.ID = w.CENTERID AND
v.VEHICLEPLATE = i.VEHICLEPLATE AND
v.VEHICLEPLATE = b.VEHICLEPLATE AND
p.ID = b.PERSON;
I want to get all the records in ITV where PEPE works.
Someone can help or orient me please?
Thank you.
Use explicit joins for your tables instead of implicit, like this:
SELECT v.VEHICLEPLATE, p.NAME
FROM ITV i
INNER JOIN VEHICLE v ON v.VEHICLEPLATE = i.VEHICLEPLATE
INNER JOIN BUYS b ON v.VEHICLEPLATE = b.VEHICLEPLATE
INNER JOIN PERSON p ON p.ID = b.PERSON
INNER JOIN CENTER c --Need join condition here
INNER JOIN WORKER w ON c.ID = w.CENTERID
WHERE w.NICK = 'PEPE';
It's a lot easier to read, and the implicit style you have in your question is depreciated.
Now you can see you are missing your join condition for INNER JOIN CENTER C. You may have further issues but start here and if it still isn't right, provide us with your current results and your expected results.

I need help formatting inner join command in SQL query

Here is my ERD for SQL Server:
https://c2.staticflickr.com/6/5832/23786188186_d6f1d93132_o.jpg
I need to find out which books are associated with each publisher.
USE BookStoreDB
SELECT ProductID
FROM Books
INNER JOIN [Publishers] PublisherID ON PublishersID = ProductID
I'm assuming I just didn't create the INNER JOIN command correctly?
SELECT p.PublisherID, b.ProductID
FROM Books b
INNER JOIN Publishers p ON p.PublisherID = b.PublisherID
The ON part of a join defines how the two tables are related to each other. In your case, it would be:
INNER JOIN Publishers ON (Books.PublisherID = Publishers.PublisherID)
If you put something between the name of the table, and the ON, it's treated as an alias. You can (and should) also use these aliases in your SELECT
FROM Books B
INNER JOIN Publishers P ON (B.PublisherID = P.PublisherID)
Finally, you probably want to select information that will actually tell you who the publisher is:
SELECT B.ISBN, P.CompanyName
FROM Books B
INNER JOIN Publishers P ON (B.PublisherID = P.PublisherID)

SQL - Multi-part identifier could not be bound

Can anyone tell me why I am getting this error?
SELECT C.ClientID, C.ClientCode, C.FullName, E.FullName AS EmployeeName
FROM ClientID C, EmployeeInfo E, tmntClientTreatmentInfo T, CliniciansClients CC
JOIN CliniciansClients
ON CliniciansClients.ClientID = ClientID.ClientID
JOIN ClientID
ON ClientID.ClientID = CliniciansClients.ClientID
JOIN EmployeeInfo
ON EmployeeInfo.EmployeeID = CliniciansClients.EmployeeID
JOIN tmntClientTreatmentInfo
ON tmntClientTreatmentInfo.ClientID = ClientID.ClientID
The multi-part identifier "ClientID.ClientID" could not be bound. // Line 6
Tony, there are lots of ways to do selects with joins and many different types of joins. But I would recommend you start by doing something basic, making sure it works, then if it's not performant or brings back duplicate data, start optimizing the joins or work on your normalization / denormalization. After a while, you'll get the hang of it. Until then, I quickly set up a postgres instance in Docker, created the tables you referenced, and this query should work:
SELECT C.ClientID, C.ClientCode, C.FullName, E.FullName AS EmployeeName
FROM ClientID C
JOIN CliniciansClients AS CC
ON CC.ClientID = C.ClientID
JOIN EmployeeInfo AS E
ON E.EmployeeID = CC.EmployeeID
JOIN tmntClientTreatmentInfo as leonardo
ON leonardo.ClientID = C.ClientID

Best practice for joining tables with case

I need to join two different tables in two different situations. In this scenario I have to solve my problem with these two solutions;
1) I will create a statement(S.ShipmentType) to use in join like this:
SELECT S.*, P.*
,CASE
WHEN S.ShipmentType = 'import' THEN SP.SupplierName
WHEN S.ShipmentType = 'export' THEN C.CustomerName
END AS ShipmentDesination
FROM tblShippments S
INNER JOIN tblProducts P ON S.productId = P.productID
LEFT OUTER JOIN tblCustomers C ON S.companyId = C.customerId AND S.ShipmentType = 'export'
LEFT OUTER JOIN tblSuppliers SP ON S.companyId = SP.supplierId AND S.ShipmentType = 'import'
2) Or I will create two different shipments tables for imports and exports, then use two different queries to get data.
Which one is the best practice?
I think I would do this with two separate queries, but I don't hate this solution either. I think it's both feasible.
Btw, I think you should be able to solve this without the CASE WHEN, assuming that CompanyId is unique over both tblCustomers and tblSuppliers. In that case you could simply do:
COALESCE(SP.SupplierName, C.CustomerName)