Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pros / Cons of MySql JOINS

Tags:

join

select

mysql

When I'm selecting data from multiple tables I used to use JOINS a lot and recently I started to use another way but I'm unsure of the impact in the long run.

Examples:

SELECT * FROM table_1 LEFT JOIN table_2 ON (table_1.column = table_2.column)

So this is your basic LEFT JOIN across tables but take a look at the query below.

SELECT * FROM table_1,table_2 WHERE table_1.column = table_2.column

Personally if I was joining across lets say 7 tables of data I would prefer to do this over JOINS.

But are there any pros and cons in regards to the 2 methods ?

like image 539
RobertPitt Avatar asked Aug 29 '10 16:08

RobertPitt


People also ask

What would be the benefits for joining tables?

The main advantage of a join is that it executes faster. The performance increase might not be noticeable by the end user. However, because the columns are specifically named and indexed and optimized by the database engine, the retrieval time almost always will be faster than that of a subquery.

Should I avoid joins?

Joins are slow, avoid them if possible. You cannot avoid joins in all cases, joins are necessary for some tasks. If you want help with some query optimizing, please provide more details. Everything matters: query, data, indexes, plan, etc.

Why use subqueries instead of joins?

If you need to combine related information from different rows within a table, then you can join the table with itself. Use subqueries when the result that you want requires more than one query and each subquery provides a subset of the table involved in the query.


1 Answers

Second method is a shortcut for INNER JOIN.

 SELECT * FROM table_1 INNER JOIN table_2 ON table_1.column = table_2.column

Will only select records that match the condition in both tables (LEFT JOIN will select all records from table on the left, and matching records from table on the right)

Quote from http://dev.mysql.com/doc/refman/5.0/en/join.html

[...] we consider each comma in a list of table_reference items as equivalent to an inner join

And

INNER JOIN and , (comma) are semantically equivalent in the absence of a join condition: both produce a Cartesian product between the specified tables (that is, each and every row in the first table is joined to each and every row in the second table).

However, the precedence of the comma operator is less than of INNER JOIN, CROSS JOIN, LEFT JOIN, and so on. If you mix comma joins with the other join types when there is a join condition, an error of the form Unknown column 'col_name' in 'on clause' may occur. Information about dealing with this problem is given later in this section.

In general there are quite a few things mentioned there, that should make you consider not using commas.

like image 122
Mchl Avatar answered Oct 05 '22 20:10

Mchl