tags:

views:

49

answers:

2

I have two tables.

table_x:

id    INT(11)
tag   INT(11)

table_tags:

id    INT(11)
name  VARCHAR(255)

Then I use PHP to perform the following query:

SELECT * FROM table_x LEFT JOIN table_tags ON table_x.tag = table_tags.id

The only problem is: how do I access table_x.id and table_tags.id in the results?

Here is the PHP code:

$query = "SELECT * FROM table_x LEFT JOIN table_tags ON table_x.tag = table_tags.id";
$results = mysql_query($query);

while($row = mysql_fetch_array($results))
{
    // how do I now access table_x.id and table_tags.id ???
}
+4  A: 

You name the columns in your column list:

SELECT 
  table_x.id AS x_id, 
  table_tags.id AS tag_id,
  other, columns, here
FROM table_x LEFT JOIN table_tags 
ON table_x.tag = table_tags.id

In general, it's considered good form to name the columns you want returned explicitly rather than relying on * (which may cause the actual number, order, and names of columns to change if the underlying table structure changes). At the same time, you can alias the column with new names in the result set for ease of use (the AS keyword is optional in most SQL dialects).

Update: OP states in a comment that he must use "*". Although this is not recommended, you can do this:

SELECT 
  table_x.id AS x_id, 
  table_tags.id AS tag_id,
  *
FROM table_x LEFT JOIN table_tags 
ON table_x.tag = table_tags.id

which combines both the named columns you want and the (bad) "*" technique. Your columns will be included in the result set twice, in the first two column positions and in their regular positions in the column list. The values will be the same.

Larry Lustig
Is there any other way? I really need to use `*` in my query.
George Edison
+1 You beat me to it larry
Jud Stephenson
You ought not to use *. But, if you must, you should be able to get the column values using an integer index into each row's worth of data. Of course, you will be completely dependent on column number and order, and your code will break in the future. You may also be able to iterate over a list of returned column names in your result data set, but I don't know if that information includes the name of the source table.
Larry Lustig
Oh, one other idea: SELECT col1 AS name1, col2 as name2, * FROM . . . combines both techniques.
Larry Lustig
Oh, perfect! Too late though... I just changed the code to not use `*` which is a good idea anyway. Thanks for the tip, though.
George Edison
+1  A: 

Use it like this

$query = "SELECT (table_x.id) AS xid, (table_tags.id) AS tid FROM table_x LEFT JOIN table_tags ON table_x.tag = table_tags.id";

$results = mysql_query($query);

while($row = mysql_fetch_array($results)) {

**//fetch id of table_x with xid**

 **echo "table_x id: ".$row['xid'];**

//fetch id of table_tags with tid

 **echo "table_tags id: ".$row['tid'];**

}

nik