问题描述:

I have two simple tables T1 and T2 both of datas coming by uploading. I want to display the file_name under a specific user_id.

T1

-------------------------

ID user_id admin_id

1 5 11

2 6 11

3 5 11

T2

--------------------------

ID user_id file_name

1 5 orange

2 6 apple

3 5 banana

My problem is it would display twice the echo as below, instead of only once. What is the best way to do this? Do I have to use inner join? Or is it possible to use only 2 for each loop. Sorry for a noob question.

orange

banana

orange

banana

Here is my sample:

$test1 = select user_id,admin_id FROM T1;

for($test1 as $key => $value)

{

$test2 = select user_id,file_type FROM T2;

foreach($test2 as $key => value2)

{

if(test1->user_id==test2->user_id)

{

$test2 = select user_id,file_name FROM T2;

echo $test2->file_name.'<br>';

}

}

}

网友答案:

First, you totally missed the php syntax in your sample (talking about the query strings), secondly there isn't any request to your mysql (or whatever sql) server.

For your SQL command you should read about the JOIN command that exists in SQL http://www.w3schools.com/sql/sql_join.asp Here is a good site to start with it. Its detailed and provides good examples

For your question about inner join: no you need left join (correct me if im wrong) and join on user_id. I won't use 2 queries + loops cause the connection is the slowest thing in a whole database transaction. The command itself will be done in about no time

相关阅读:
Top