0

I want to design a query where I want to fetch a name from a second table based on the id from the first table. I am able to get the result using the following two queries.

Please, Let me know which one is efficient or gives fast result and why.

SELECT r1.id, c1.categoryName
FROM request r1 
LEFT JOIN category c1
ON r1.categoryId = c1.id
order by r1.dateCreated DESC;


SELECT id, (SELECT categoryName FROM category WHERE id 
= categoryId)
FROM request r1
order by dateCreated DESC;
Squirrel
  • 23,507
  • 4
  • 34
  • 32
Awais Ahmad
  • 378
  • 1
  • 4
  • 17

1 Answers1

0

Normaly, explicit joins are the faster way to go, because the optimisation is better, but nowdays optimisers are getting better all the time, so you can try to go with a more readable SQL query.

You can find this in the manuals (13.2.10.11 Rewriting Subqueries as Joins): https://dev.mysql.com/doc/refman/5.7/en/rewriting-subqueries.html

It says "A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better".

But in complex cases I prefer subquery, they have more readability, and your SQL will be more maintainable, Sub-queries are the logically correct way to solve problems.

UHDante
  • 577
  • 9
  • 21