Welcome to WebmasterWorld Guest from 174.129.163.89

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

get data from join statement

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

Junior Member

5+ Year Member

joined:July 8, 2008
posts: 80
votes: 0


hi!
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?

like-

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)

Junior Member

5+ Year Member

joined:July 8, 2008
posts:80
votes: 0


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)

Senior Member

WebmasterWorld Senior Member 5+ Year Member

joined:May 31, 2008
posts:661
votes: 0


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

Junior Member

5+ Year Member

joined:July 8, 2008
posts:80
votes: 0


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)

Administrator

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

joined:July 31, 2003
posts:12547
votes: 2


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
column1
column2

TableB 
id
column2
column3

SELECT 
TableA.id AS aid,
column1,
TableA.column2 AS acolumn2,
B.column2 AS bcolumn2,
column3
FROM TableA
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)

Junior Member

5+ Year Member

joined:July 8, 2008
posts:80
votes: 0


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

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members