Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

get data from join statement

7:57 am on Jan 13, 2009 (gmt 0)

5+ Year Member

say I'v two tables a and b. Both tables hv a column named 'id'.
after joining des two how can I retrieve the id of table a for example?


while($row = mysql_fetch_assoc($result))
$a_id = $row['#*$!']; // here wat should '#*$!' be?

thanks in advance..!

7:58 am on Jan 13, 2009 (gmt 0)

5+ Year Member

SELECT * FROM a as aa join bb as at on aa.val1 = bb.val2 where c = 'somethin'

is my join statement

8:04 am on Jan 13, 2009 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member

select aa.id AS aid, at.id AS bid ....
8:12 am on Jan 13, 2009 (gmt 0)

5+ Year Member

Im sorry its not very clear. I want help in tryin to get the data searched by the query.
5:03 pm on Jan 14, 2009 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

janharders demonstrated that the column name (or alias if an alias is used) is one way to use the associative index in a mysql fetch. So, using mysql_fetch_assoc() the following example shows how you use the associative index name from your query. First, some simple tables for our example ...


TableA.id AS aid,
TableA.column2 AS acolumn2,
B.column2 AS bcolumn2,
INNER JOIN TableB AS B ON (TableA.id = TableB.id)

In your PHP while loop, you can refer to them like so ...
while($row = mysql_fetch_assoc($result)) 
$a_id = $row['aid']; // TableA.id
$column1 = $row['column1']; // TableA.column1
$acolumn2 = $row['acolumn2']; // TableA.column2
$bcolumn2 = $row['bcolumn2']; // TableB.column2
$column3 = $row['column3']; // TableB.column3

A number of techniques are demonstrated here. First, notice how both tables have some identical column names? We can use an alias on the column names so as to differentiate between the two. The columns are called ambiguous and by using an alias we can remove the ambiguity. We can also use an alias on a table name. You see that here when I use an alias for TableB. Now, whatever the column name, or alias name if used, is the index we use in our fetching control structure.
8:33 am on Feb 2, 2009 (gmt 0)

5+ Year Member

thanks a lot. I didnt go ahead with this method at that time. but will have a look n learn now. thanks again