Skip to content
Advertisement

Are there faster alternatives to the CROSS JOIN model used below?

All I know is CROSS JOIN, but sometimes I look on StackOverflow for query support and find some answer mentioning that this is not the best join. I don’t know if they’re saying that due to an opinion on what would be easier on the developer, or if CROSS JOIN is functionally inferior to its JOIN brethren. Please tell me if refactoring with another JOIN model (LEFT? INNER? x?) should result in better performance for the query example below. (Constructive criticism towards other optimizations I may not even be aware to ask about would also not go amiss)

Advertisement

Answer

CROSS JOIN generates a lot of rows, if there is no filtering. For that reason, it tends to be discouraged. Sometimes it is necessary.

In your case, you have bona fide joins. And you should learn how to use them.

For instance, for this condition:

is better written as:

Why is this better? It puts the connection between the tables right next to where the tables are defined in the JOIN clause. Most databases enforce the presence of ON, which helps ensure that you don’t accidentally forget a condition.

That said, the MySQL optimizer is smart enough to turn your syntax into JOIN. However, I strongly recommend that you learn the proper, standard, readable JOIN syntax. Then you can learn about outer joins, which makes this syntax more powerful.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement