Can't display column from different table - mysql

I am trying to display the driver's first and last name but when I run this query the name columns just return test and not the actual names from the employee table
SELECT checklistitem.*,
m1.Company_ID AS Company_ID,
m1.ChecklistID As ChecklistID,
e.FirstName As FirstName,
e.LastName As LastName
FROM checklistitem
LEFT JOIN employee e ON e.CompanyID
LEFT JOIN maintenance m1 ON m1.CheckListID
LEFT JOIN Vehicle v ON m1.LinkedID = v.ID
LEFT JOIN Trailer t ON m1.LinkedID = t.ID
WHERE m1.Company_ID = 129
I thought maybe the table wasn't linking correctly to find the names so I tried changing the code to LEFT JOIN employee e ON m1.Company_ID because both the maintenance and the employee table have a company ID but I get the error
Unknown column 'm1.Company_ID' in 'on clause'

Your issue is with the LEFT JOIN statements. You have an invalid syntax in your ON clause.
FROM checklistitem
LEFT JOIN employee e ON e.CompanyID /*ERROR*/
LEFT JOIN maintenance m1 ON m1.CheckListID /*ERROR*/
Your SQL statement has to be table.column = table2.column
So I'm gonna go out on a guess and say you should being using
FROM checklistitem
LEFT JOIN employee e ON checklistitem.CompanyID = e.CompanyID
LEFT JOIN maintenance m1 ON e.CheckListID = m1.CheckListID
Please note: I don't know what your tables are setup like. checklistitem.CompanyID and e.CheckListID was a guess. Please replace those with the correct fields from your tables.
Also with your table names, m1.Company_ID will automatically turn into Company_ID. No need to use AS.

Related

Query code shows nothing after adding a new relationship

I have relationship between Student.Department and Departments.Id, Student.Faculty and Faculties.Id. Below code was working before I created a new relationship between Departments.facultyId and Faculties.Id
SELECT
*
FROM
Students sd
INNER JOIN Departments dp
ON sd.Department = dp.Id
INNER JOIN Faculties fd
ON sd.Faculty = fd.Id
Before adding facultyIdcolumn in Departments table, I could run the query, but now the query shows nothing.
Should I also write something for relationship between fd.Idand dp.facultyId?
I just replicate your database structure and the relationships. Your query working pretty well. If it doesn't work, make sure you have data to support your query. I mean in all tables since you are having left joins from faculty and department with student table. You can see the result for the query below.
SELECT * FROM student sd INNER JOIN department dp ON sd.dept = dp.id INNER JOIN faculty fd ON sd.fac = fd.id
Just to clarify it, I have 8 students (2 for each department), 4 facutlties (2 for each faculty) and 2 faculties. So it works. Check whether your DB has data to satisfy the query constraints.
First, verify this join:
SELECT
*
FROM
Students sd
LEFT JOIN Departments dp
ON sd.Department = dp.Id
If cannot see Departments information, verify that sd.Department has the correct values.
Do the same with Faculties
SELECT
*
FROM
Students sd
LEFT JOIN Faculties fd
ON sd.facultyId = fd.Id
Using LEFT JOIN you'll see all records of the first table, and only the records of second table that match the ON clause.
And finally check the new relation:
SELECT
*
FROM
Dapartments dp
LEFT JOIN Faculties fd
ON dp.facultyId = fd.Id

SQL Unknown column, despite it definitely being there - SQL Error (1054)

I am having an issue with my sql, I am trying to display a user based of their age group, attaching the string along with the primary key, but i only want that one value to be shown
I believe it is something like this
SELECT users.gbpfid,
users.aid,
compresults.total,
agegroup.aid AS aid2
FROM compresults
INNER JOIN competitions
ON competitions.cid = compresults.cid
INNER JOIN agegroup
ON agegroup.aid = users.aid
INNER JOIN users
ON compresults.gbpfid = users.gbpfid
WHERE competitions.compdate = (SELECT competitions.compdate
FROM competitions
INNER JOIN compresults
ON compresults.cid =
competitions.cid
WHERE compresults.gbpfid = users.gbpfid
ORDER BY competitions.compdate DESC
LIMIT 1)
however this throws up this error
SQL Error (1054): Unknown column 'users.aid' in 'on clause'
Which i cannot make any sense
when i remove the
"on agegroup.aid = users.aid" from line 5
it displays the records, but for each aid
I am confused how it recognises the column without the inner join (specifying the connection) but when i do whole inner join of the agegroup table, it joins fine, but with all the records
any ideas? thanks
You are trying to join agegroups using users.aid before users table is even joined.
INNER JOIN competitions
ON competitions.cid = compresults.cid
INNER JOIN agegroup
ON agegroup.aid = users.aid
INNER JOIN users
ON compresults.gbpfid = users.gbpfid
As you can see you are truing to access users.aid before is joined. Change order of the joins to:
competitions -> users -> agegroup
This should work:
INNER JOIN competitions
ON competitions.cid = compresults.cid
INNER JOIN users
ON compresults.gbpfid = users.gbpfid
INNER JOIN agegroup
ON agegroup.aid = users.aid
You should be able to access users.aid now.
Hope this helps.
The cause of the isue is that joins are processed from left to right. In your code you have the following order:
INNER JOIN agegroup
ON agegroup.aid = users.aid
INNER JOIN users
So, in the ON agegroup.aid = users.aid you reference the users table before it is joined to the fray.
Change the order of the joins:
compresults -> competitions -> users -> agegroup

If row exist in a table then use another tables value in SQL

What i would like to archieve:
Getting the correct sum of the total amount of the orders that has been cancelled of user id 2002.
Some pre information:
I am having deals which that has its price in deals.price and its id in deals.ID
I then have orders with a foreign key to deals.ID
Running this SQL:
select SUM(deals.price), orders.* from orders
JOIN deals ON deals.ID = orders.deal_id
where orders.user_id = 2002
and orders.cancelled = 1
Works just fine.
Here is where i get stuck:
As an addition to deals, each deals has products with their own prices.
Table is called deal_products, deal_products.price hold the price and deal_products.product_id has the ID of it.
A order is attached to a deal product in another table called order_products, where order_products.product_id = deal_products.product_id
To sum up: I would like to do is including a if inside the above SQL.
If a order has a row in order_products, get the order_products.product_id and find the price in deal_products (price) and use this instead of deals.price when SUM()'ing.
If there is no row it should use deals.price.
How can this be archieved? To first look in another table if there is a entry, and then further look in to a third table and get a value to use?
You can use COALESCE + LEFT JOIN:
select SUM(coalesce(dp.price, d.price)), o.*
from orders o JOIN deals d ON d.ID = o.deal_id
LEFT JOIN order_products op on op.order_id = o.id
LEFT JOIN deal_products dp on op.product_id = dp.product_id
where o.user_id = 2002 and o.cancelled = 1
group by ...;
COALESCE function returns first not null operand
LEFT [OUTER] JOIN = [INNER] JOIN + all rows of the structure on the left side of the LEFT JOIN keyword, which don't match the ON clause in the right structure.

mySQL- how to show all contact and their status by using INNER JOIN

This is my company Table
CompanyID, CompanyName
This is my Contact Table
ContactID, ContactName, CompanyID
This is my Report Table
ReportID, ReportName
This is my ReportContact Table, Many to Many Relationship
ContactID, ReportID
I want to return all ALL my CONTACTID of 1 company, include those who are not assign to any report, I also want to return the reportID that are assign to different contacts
1 contacts can be assign to many reports
1 reports can consist of many contacts
My current SQL CODE only manage to get the 2 contactID in the ReportContactTable
SELECT rc.ContactID, rc.ReportID from contact c INNER JOIN Reportcontact rc on c.ContactID = rc.ContactID Where CompanyID=1
how can Return all the contact include those not in the reportcontact table, but get the reportID at the same times?
INNER JOIN filters out those rows that are not in ReportContact. Try to use LEFT JOIN if you want all contacts from contact table.
SELECT rc.ContactID, rc.ReportID
FROM contact c LEFT JOIN Reportcontact rc
ON c.ContactID = rc.ContactID
WHERE CompanyID = 1
I'm not 100% sure I understand what you are trying to do, but if you want all rows from the contact table then you need to use an OUTER rather than INNER join.
Try changing the word INNER to LEFT.
An INNER join ensures that rows that satisfy the join condition appear in both tables.
An OUTER join says "show me all the rows in one table, plus those that satisfy the join condition from the other table". Which table shows all the rows depends on the use of the keywords LEFT and right
a left join b on a.id = b.id will show all rows from table a plus those from b which satisfy the join condition
a right join b on a.id = b.id will show all rows from table b plus those from a which satisfy the join condition

Working with complicated joins in MySQL

Here is the schema of the database I'm working with - [redacted]
I'm trying to come up with 2 different queries for 2 different result sets -
Sales representatives with the highest sales
Sales representatives with the highest sales grouped by managerId
I've had some luck with the 1st query; this is what I came up with:
SELECT
SUM(`products`.`cost`) AS `Sale`
, `employees`.`firstName`
FROM
`d2dpro`.`sales_reps`
, `d2dpro`.`products`
INNER JOIN `d2dpro`.`employees`
ON (`sales_reps`.`employeeId` = `employees`.`employeeId`)
INNER JOIN `d2dpro`.`sold_products`
ON (`products`.`productId` = `sold_products`.`productId`)
INNER JOIN `d2dpro`.`sales`
ON (`sold_products`.`saleId` = `sales`.`saleId`) AND (`sales`.`salesCampId` = `sales_reps`.`saleCampId`)
GROUP BY `employees`.`firstName`;
With this query, I'm stuck with this error:
Error Code: 1054
Unknown column 'sales_reps.saleCampId' in 'on clause'
Any help with this query? And also for the 2nd one?
You are using one table (sales_reps) that is CROSS JOIN-ed with the INNER JOIN of the tables employees, sold_products and sales. To be able to reference sales_reps in that JOIN you should include it as inner join: (the FROM clause should look like this)
FROM `d2dpro`.`products`
INNER JOIN `d2dpro`.`employees`
ON (`sales_reps`.`employeeId` = `employees`.`employeeId`)
INNER JOIN `d2dpro`.`sold_products`
ON (`products`.`productId` = `sold_products`.`productId`)
INNER JOIN `d2dpro`.`sales`
ON (`sold_products`.`saleId` = `sales`.`saleId`)
INNER JOIN `d2dpro`.`sales_reps`
ON (`sales`.`salesCampId` = `sales_reps`.`saleCampId`)