ON statement in sql for joins - mysql

Good day! I'm searching the entire web for the purpose of 'on' statement in MySQL. But i can't find an exact answer about the purpose of it. For example:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
What i'm trying to trace is to find the purpose of this:
ON Customers.CustomerID=Orders.CustomerID

You should not look for the ON syntax but for the inner join syntax and there you will find a lot explanations on line. E.g. http://www.w3schools.com/sql/sql_join_inner.asp
The 'ON' in this case is similar to 'Where' It defines on which fields the join is based.

I guess you are fooled by the fact that in your particular case, the joining field name is the same in both table: CustomerID.
That is not always the case, hence the necessity of specifying in SQL which fields are used for joining tables, in the ONclause.

You are joining two tables on customerId.
It means that you will join two tables side by side having same customerId from both the tables, so you could select customer and their order together at the same time.

Related

Can the usage of inner join be avoided in MySQL?

After reading the question title you may find it silly but I'm seriously asking this question with curiosity in my mind.
I'm using MySQL database system.
Consider below the two tables :
Customers(CustomerID(Primary Key), CustomerName, ContactName, Address, City, PostalCode, Country)
Orders(OrderID(Primary Key), CustomerID(Foreign Key), EmployeeID, OrderDate, ShipperID)
Now I want to get the details of all orders that is which order is placed by which customer?
So, I did it in two ways :
First way:
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerID=o.CustomerID;
Second way:
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
In both the cases I'm getting exactly the same correct result. My question is why there is a necessary of additional and confusing concept of Inner Join in MySQL as we can achieve the same results even without using Inner Join?
Is the Inner Join more effective in any manner?
What you are looking at is ANSI-89 syntax (A,B WHERE) vs ANSI-92 syntax (A JOIN B ON).
For very simple queries, there is no difference. However, there are a number of things you can do with ANSI-92 that you cannot do or that become very difficult to implement and maintain in ANSI-89. Anything more than two tables involved, more than one condition in the same join, or separating LEFT JOIN conditions from WHERE conditions are all much harder to read and work with in the older syntax.
The old A,B WHERE syntax is generally considered obsolete and avoided, even for the simple queries where it still works.
The trade-offs of hardware optimization are second to none to users being able to maintain their queries.
Having explicit clean code is better than having esoteric implicit code. In actual production relational databases, most of the queries that take too long come from the ones where the tables are in a concatenated list. These queries show that:
User did not put the effort on expressing the order these tables are joined.
All the relationship joins are cluttered in one place instead organized on its own space for each join.
If all queries are in such format for said user, user does not take
advantage of Outer Joins. There are many cases where a relationship between tables can be: (1) TO (0-many) OR (many) TO (many) instead of (1) TO (1-many).
As in most use cases, these queries become to start to be a problem when the number of joins increase. Beginner users choose to query the tables by placing them as a list delimited with a comma because it takes less to type. At first, it does not seem to be a problem because they are joined against two to three tables. This in turn become a habit to the beginner user. As they start to write more complicated queries by increasing their number of joins, those type of queries are harder to maintain as described from the above bullet points.
Conclusion: As the number of joins within a query scales, improper indentation and categorization make the query harder to maintain.
You should use INNER JOIN and ident your query as below so it is easy for others to read:
SELECT
Orders.OrderID,
Orders.OrderDate,
Customers.CustomerName
FROM Orders
INNER JOIN Customers
ON Customers.CustomerID = Orders.CustomerID;

Explain which table to choose "FROM" in a JOIN statement

I'm new to SQL and am having trouble understanding why there's a FROM keyword in a JOIN statement if I use dot notation to select the tables.columns that I want. Does it matter which table I choose out of the two? I didn't see any explanation for this in w3schools definition on which table is the FROM table. In the example below, how do I know which table to choose for the FROM? Since I essentially already selected which table.column to select, can it be either?
For example:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
The order doesn't matter in an INNER JOIN.
However, it does matter in LEFT JOIN and RIGHT JOIN. In a LEFT JOIN, the table in the FROM clause is the primary table; the result will contain every row selected from this table, while rows named in the LEFT JOIN table can be missing (these columns will be NULL in the result). RIGHT JOIN is similar but the reverse: rows can be missing in the table named in FROM.
For instance, if you change your query to use LEFT JOIN, you'll see customers with no orders. But if you swapped the order of the tables and used a LEFT JOIN, you wouldn't see these customers. You would see orders with no customer (although such rows probably shouldn't exist).
The from statement refers to the join not the table. The join of table will create a set from which you will be selecting columns.
For an inner join it does not matter which table is in the from clause and which is in the join clause.
For outer joins it of course does matter, as the table in the outer join is allowed to have "missing" records.
It does not matter for inner joins: the optimizer will figure out the proper sequence of reading the tables, regardless of your choice for the ordering.
For directional outer joins, it does matter, because these are not symmetric. You choose the table in which you want to keep all rows for the first FROM table in a left outer join; for the right outer join it is the other way around.
For full outer joins it does not matter again, because the tables in full outer joins are used symmetrically to each other.
In situations when ordering does not matter you pick the order to be "natural" to the reader of your SQL statement, whatever that means for your model. SQL queries very quickly become rather hard to read, so the proper ordering of your tables is important for human readers of your queries.
Well in your current example the from operator can be applied on both tables.
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers,Orders
WHERE Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
->Will work like your code
The comma will join the two tables.
From just means which table you are retrieving data from.
In your example, you joined the two tables using different syntax.
it could also have been :
SELECT Customers.CustomerName, Orders.OrderID
FROM Orders
INNER JOIN Customers
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
all the code written will generate same results

JDBC mySQL DML Error

I am trying display all the relevant information for jobs done to a customer using a JOIN TABLE QUERY.
Here is my code...
SELECT Bill.BillID, Duty.TaskTime
FROM Invoice
LEFT OUTER JOIN Duty.JobID = Bill.JobID
WHERE Job.CustomerID = Customer.CustomerID
I keep getting this error...
'#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.JobID WHERE Job.CustomerID = Customers.CustomerID' at line 3'
The problem is that you are trying to access tables that you haven't told the query about in both your WHERE and SELECT clauses. When you say Bill.BillID in your SELECT clause, you're saying that you want the Field BillID from the table called Bill.
The rule your syntax is breaking is that you can't use a table name in the SELECT or WHERE clauses, unless you've mentioned it in the FROM clause (or a JOIN).
So now, let's look at your query.
SELECT Bill.BillID, Duty.TaskTime
FROM Invoice
LEFT OUTER JOIN Duty.JobID = Bill.JobID
WHERE Job.CustomerID = Customer.CustomerID
This means that you want to pick fields from the tables named Bill and Duty, and filter the results based on fields from the Job and Customer tables. However, you've only mentioned one table by name in the FROM clause (Invoice). You've almost joined the Duty table, but you're joining it to a place in a table you haven't mentioned yet (Bill). I'm going to guess that you intend to use Bill as an alias for Invoice. That would mean that what you really want is more like:
// Still incorrect
SELECT Bill.BillID, Duty.TaskTime
FROM Invoice AS Bill
LEFT OUTER JOIN Duty ON Duty.JobID = Bill.JobID
WHERE Job.CustomerID = Customer.CustomerID
But we still haven't mentioned either the Job or Customer tables that are referenced in the WHERE clause. In order to use them, you need to JOIN those tables as well. We'd need to know more about your schema to figure out how to do that, but I can tell you that you'll need at least two more JOIN clauses. Assuming that you have a CustomerID field on the Invoice table, we probably want to join like this.
// speculative
SELECT Bill.BillID, Duty.TaskTime
FROM Invoice AS Bill
LEFT OUTER JOIN Duty ON Duty.JobID = Bill.JobID
JOIN Customer ON Customer.CustomerID = Bill.CustomerID
JOIN Job ON // Well, something...We don't know.
I strongly recommend you spend some time reading and studying the excellent Wikipedia entry on SQL JOINs. Good luck~
Your mistake is how you point your tables, maybe:
FROM Invoice as Bill LEFT OUTER JOIN NameTable2 as Duty ON Dury.JobID=Bill.JobID

MySQL joins confuse me and I always get syntax errors

I need to fetch some data from a MySQL db. I have the function working using two separate, simple queries, but i'm sure this is probably achievable with one query using a JOIN. SQL isn't my strong point and I keep getting syntax errors when I try. Sure, I could leave it as it is, why not, it works. But i would prefer to see a real world example of how they can be joined so i can try and apply it on other queries in the future.
Query one is:
select manufacturers_id from products where products_name = product a
The result is then put into a variable and used in the following
select manufacturers_name from manufacturers where manufacturers id = $man_id
So, basically, the products table holds the manufacturers_id, which we need to collect for a given product to find out what the manufacturers name is from the manufacturers table.
manufacturers_id is the common field.
Try this:
SELECT b.manufacturers_name
FROM products a
LEFT JOIN manufacturers b ON a.manufacturers_id = b.manufacturers_id
WHERE a.products_name = 'PRODUCT NAME'
Below is a diagram of SQL Joins
Image Source
Try this:
select m.manufacturers_name from products p, manufacturers m
where p.products_name = 'productA' and p.manufacturers_id = m.id
I believe this is what you're looking for
SELECT manufacturers.manufacturers_name
FROM products
JOIN manufacturers on manufacturers_id=products.manufacturers_id
WHERE manufacturers_name='product a'
With a join, you just need to follow this syntax, and remember that you have to set the matching columns equal to each other so you don't end up with invalid rows.
I'd show you how the equivalent of this using table joins, but I really don't want to encourage the use of that syntax, even by accident.

what is difference between 'where' and different 'joins' in mysql? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
In MySQL queries, why use join instead of where?
Joins are always confusing for me..can anyone tell me what is difference between different joins and which one is quickest and when to use which join and what is difference between join and where clause ?? Plz give ur answer in detail as i already read about joins on some websites but didn't get the concept properly.
Rather than quote an entire Wikipedia article, I'm going to suggest your their article on SQL Joins.
An SQL JOIN clause combines records
from two or more tables in a
database. It creates a set that
can be saved as a table or used as is.
A JOIN is a means for combining
fields from two tables by using values
common to each. ANSI standard SQL
specifies four types of JOINs: INNER,
OUTER, LEFT, and RIGHT. In special
cases, a table (base table, view, or
joined table) can JOIN to itself in a
self-join.
A programmer writes a JOIN predicate
to identify the records for joining.
If the evaluated predicate is true,
the combined record is then produced
in the expected format, a record set
or a temporary table, for example.
There is an older syntax that uses WHERE clauses to imply INNER JOINs. While it works, and will produce queries that run exactly like queries specified with the INNER JOIN syntax, it is deprecated because most people find it more confusing.
Here's the documentation for the MySQL JOIN syntax.
This query:
SELECT c.customer_name, o.order_id, o.total
FROM customers c, orders o
WHERE c.id = o.customer_id
and this
SELECT c.customer_name, o.order_id, o.total
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id
make no difference on what is executed on the mysql server but the join is (imho) way more readable. Expecially for more complex joins:
Here is an article about the topic: http://www.mysqlperformanceblog.com/2010/04/14/is-there-a-performance-difference-between-join-and-where/