Everything PHP: Selecting Table Specific Fields on Joins

Published on Nov 23, 2009   //  Development
Off

Everything PHP

An organized and planned database will have relatable data separated into multiple tables. This data may need to be used together at some point. This is where MySQL JOINs come in. Carrying on with our previous instalment, we’ll continue talking about table joining.

Last time, we took a look at a basic table join, which selected all fields from two tables. Today, we’ll be covering how select specific fields from specific tables involved in our join. In your code, you may only need to use some of the available fields. By specifying just the fields you need, you can shave some time off your query. Let’s take a look at our previous join query, which we’ll modify:

[sql]SELECT * FROM table1 JOIN table2 ON table1.id = table2.id[/sql]

With this query, we use the wildcard character (an asterisk) to specify that we want all the fields. In a regular select query, we would use a comma-separated list of fields, in place of the wildcard, to retrieve specific fields. In a join query, it is the same, except with must specify the table that a field resides in. We do this in the format of: table_name.field_name. Adapting our previous example, we end up with this:

[sql]SELECT table1.id, table1.name, table2.mark FROM table1 JOIN table2 ON table1.id = table2.id[/sql]

Next time we’ll be covering joining multiple tables.