Joining tables
Even though querying MySQL is quite fast, especially if it is in the same server as our PHP application, we should try to reduce the number of queries that we will execute to improve the performance of our application. So far, we have queried data from just one table, but this is rarely the case. Imagine that you want to retrieve information about borrowed books: the table contains only IDs and dates, so if you query it, you will not get very meaningful data, right? One approach would be to query the data in borrowed_books
, and based on the returning IDs, query the book
and customer
tables by filtering by the IDs we are interested in. However, this approach consists of at least three queries to MySQL and a lot of work with arrays in PHP. It seems as though there should be a better option!
In SQL, you can execute join queries. A join query is a query that joins two or more tables through a common field and, thus, allows you to retrieve data from these tables, reducing the amount...