Smart way of writing sql Join [closed] - mysql

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I was exploring someone's code and I have found this query.This query is fetching data using join. But there is no use of inner join, outer join, left or right. The programmer simply writes this query.
I found this is the SMART way of writing query, if this query is right ?
SELECT
a.*,b.*,c.*,d.*,e.*
FROM
property_photos a,property_promotions b,properties c, communities d,cities e
WHERE
a.property_id = b.property_id AND
a.property_id = c.id AND
(b.promotion_id =2 OR b.promotion_id =1) AND
a.mainphoto="Y" AND
d.id=c.community_id AND
e.id = c.city_id AND
a.featured_status = 1
Is this query correct?
It this query is right, the i think, this is more better way to write queries since it will save a lot of disk space instead of use Left join/right Join like words which makes query long
SMARTY WAY

Yes it is alright. It is the same as an INNER JOIN.
Note:
Which Syntax to Use? Per the ANSI SQL specification, use of the INNER
JOIN syntax is preferable. Furthermore, although using the WHERE
clause to define joins is indeed simpler, using explicit join syntax
ensures that you will never forget the join condition, and it can
affect performance, too (in some cases).
Source: Sam's - MySQL Crash Course, page 139

Yes, this is known as implicit JOIN syntax. It has fallen out of favour once ANSI-92 defined an explicit JOIN syntax, which is an order of magnitude easier to read as your queries get more complex.
From Wikipedia:
SQL specifies two different syntactical ways to express joins: "explicit join notation" and "implicit join notation".
The "explicit join notation" uses the JOIN keyword to specify the table to join, and the ON keyword to specify the predicates for the join, as in the following example:
SELECT *
FROM employee
INNER JOIN department ON employee.DepartmentID = department.DepartmentID;
The "implicit join notation" simply lists the tables for joining, in the FROM clause of the SELECT statement, using commas to separate them. Thus it specifies a cross join, and the WHERE clause may apply additional filter-predicates (which function comparably to the join-predicates in the explicit notation).
The following example is equivalent to the previous one, but this time using implicit join notation:
SELECT *
FROM employee, department
WHERE employee.DepartmentID = department.DepartmentID;

Related

Cascaded LEFT JOIN v.s. sub-select

I have 2 queries:
1)
SELECT person.idx, person.name, groups.idx
FROM people
LEFT JOIN membership
ON membership.person=person.idx
LEFT JOIN groups
ON groups.name='supervisors'
AND membership.group=groups.idx
2)
SELECT person.idx, person.name, a.idx
FROM people
LEFT JOIN
(SELECT group.idx, membership.person
FROM groups, membership
WHERE membership.group=group.idx
AND group.name='supervisors') a
ON a.person=person.idx
These queries have been simplified but the core logic is the same. They seem to be equivalent. The 1st seems "cleaner" syntactically. I'm not an SQL expert, and am pretty new to LEFT JOIN in particular, but it seems to be the way to answer this kind of membership question, where one table contains a subset of information about another table. Is this the right approach?
The two queries are not the same. The first returns rows for all groups a person is a member of, with the idx of the "supervisors" where appropriate.
The second returns one row for each member, with the idx of the "supervisors" group where appropriate. You should choose the version that does what you want.
Once you have the logic that you want, then in MySQL, it is usually best to avoid subqueries in the FROM clause if possible. MySQL has a tendency to materialize them, which makes optimizations more difficult (I think this has gotten better in more recent versions).
Also, you should eschew commas in the FROM clause and always use proper, explicit, standard JOIN syntax.
Poor form to answer my own question?
This seems to work:
SELECT person.idx, person.name, groups.idx
FROM people
LEFT JOIN (groups, membership)
ON groups.name='supervisors'
AND groups.person=person.idx
AND membership.group=groups.idx
Maybe a MySQL only extension?

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;

MySQL Left Join and Right Join Optimization

I've been looking up some documentation about this topic here: https://dev.mysql.com/doc/refman/5.7/en/left-join-optimization.html
But I don't understand the following example:
The join optimizer calculates the order in which to join tables. The table read order forced by LEFT JOIN or STRAIGHT_JOIN helps the join optimizer do its work much more quickly, because there are fewer table permutations to check. This means that if you execute a query of the following type, MySQL does a full scan on b because the LEFT JOIN forces it to be read before d:
SELECT *
FROM a JOIN b LEFT JOIN c ON (c.key=a.key)
LEFT JOIN d ON (d.key=a.key)
WHERE b.key=d.key;
The fix in this case is reverse the order in which a and b are listed in the FROM clause:
SELECT *
FROM b JOIN a LEFT JOIN c ON (c.key=a.key)
LEFT JOIN d ON (d.key=a.key)
WHERE b.key=d.key;
Why does the order make an optimization? Do JOIN and LEFT_JOIN execute in some order?
I suspect the first quote is not quite correct. I have seen LEFT JOIN turned into JOIN and then the tables touched in the 'wrong' order.
Anyway, don't worry about the work the optimizer needs to do. In thousands of slow JOINs, I have identified only one case where the cost of picking the order was important. And it was a case of multiple joins to a single table; yet another drawback of EAV schema. Anyway, there is a simple setting to avoid that problem.
LEFT/RIGHT/plain JOINs are semantically done left-to-right (regardless of the order the optimizer chooses to touch the tables).
If you are concerned about the ordering, you can add parentheses. For example:
FROM (a JOIN b ON ...) JOIN (c JOIN d ON ...) ON ...
If you are using "commajoin" (FROM a,b...), don't. However, its precedence changed long ago. The workaround was to add parens so that the same SQL would work in versions before and after the change.
Don't use LEFT unless you need it to get NULLs for missing 'right' rows. It just confuses readers into thinking that you expect NULLs.
This example is wrong in many ways, and it is not clear to me what it is trying to convey. Apologies for that. I will file a bug with the documentation team.
Some clarifications:
For the given query, the last LEFT JOIN will be converted to an inner join. This is because the WHERE clause, WHERE b.key=d.key, implies that d.key can not be NULL. Hence, any extra rows produced by LEFT JOIN compared to INNER JOIN would be filtered out by the WHERE clause. (The principles of this transformation is described in the paragraph following the given example.)
The ON clause of the first LEFT JOIN, ON (c.key=a.key), makes table c dependent on table a, but not table b. Hence, the only the requirement wrt join order is that table a is processed before table c. The order in which tables a and b are listed in the query, will not change that.
Tables b and d may be processed in any order, both wrt each other and wrt the other tables of the query.
This paragraph seems to recommend LEFT JOIN as a mechanism to reduce number of "table permutations to check". This is not meaningful since changing from INNER JOIN to LEFT JOIN may change the semantics of the query. For this purpose STRAIGHT_JOIN should be used instead.
For most join queries, execution time by far exceeds optimization time. Reducing the number of "table permutations to check" may cause potentially more efficient permutations to not be explored. Hence, LEFT JOIN should not be used unless it is required to get the wanted semantics.

Is this a MySQL JOIN? [duplicate]

This question already has answers here:
Explicit vs implicit SQL joins
(12 answers)
Closed 8 years ago.
SELECT
dim_date.date, dim_locations.city, fact_numbers.metric
FROM
dim_date, fact_numbers
WHERE
dim_date.id = fact_numbers.fk_dim_date_id
AND
dim_locations.city = "Toronto"
AND
dim_date.date = 2010-04-13;
Since I'm not using the JOIN command, I'm wondering if this is indeed a JOIN (and if not, what to call it)?
This is for a dimensional model by the way which is using surrogate and primary keys to match up details
Yes, it is joining the tables together so it will provide related information from all of the tables.
The one major downfall of linking tables via WHERE instead of JOIN is not being able to use LEFT, RIGHT, and Full to show records from one table even if missing in the other.
However, your SQL statement is invalid. You are not linking dim_locations to either of the other tables and it is missing in the FROM clause.
Your query using an INNER JOIN which is comparable to your WHERE clause may look something like the following:
SELECT DD.date, DL.city, FN.metric
FROM dim_date AS DD
JOIN fact_numbers AS FN ON DD.id = FN.fk_dim_date_id
JOIN dim_locations AS DL ON DL.id = FN.fk_dim_locations_id
WHERE DL.city = 'Toronto'
AND DD.date = 2010-04-13
yes, it is joining tables. It is called non-ANSI JOIN syntax when join clause is not used explicitly. And when join clause is used, it is ANSI JOIN
If you reference two different tables in a where clause and compare their referential IDs, then yes, it acts the same as a JOIN.
Note however that this can be very inefficient if the optimizer doesn't optimize it properly see: Is there something wrong with joins that don't use the JOIN keyword in SQL or MySQL? and INNER JOIN keywords | with and without using them

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/