显示2个表中的数据

时间:2013-05-28 06:32:02

标签: php mysql

我有两张表,我需要以下列方式显示一些数据:

从Table1,我想选择具有相同id_ref的所有用户。 在我选择它们之后,我想显示它们的数字,然后在列表中显示它们中的每一个,并且还显示它们在Table2中有多少行,但不是它们的所有行,只有某些符合我条件的行。另外,我想显示从Table2中选择的行的ID。我的代码是:

    $query = 'SELECT * FROM Table1  WHERE id_ref = '.$id_user.' AND active = 1 AND approved = 1 ORDER BY `id_aff` DESC';
$users_brought = mysql_query($query, $conn) or die(mysql_error());
$num_users_brought  = mysql_num_rows($users_brought);  


    while($user_bro = mysql_fetch_assoc($users_brought)):


    $query = 'SELECT * FROM Table2 WHERE id_aff = '.$user_bro['id_aff'].' AND ref = '.$income['id_user'].
$user_bro_brought = mysql_query($query, $conn) or die(mysql_error());
$num_user_bro_brought = mysql_num_rows($user_bro_brought); 

但有些事情没有用......有什么想法吗?

2 个答案:

答案 0 :(得分:0)

此行中有语法错误

$query = 'SELECT * FROM Table2 WHERE id_aff = '.$user_bro['id_aff'].' AND ref = '.$income['id_user'].

您应该将其格式化为

$query = 'SELECT * FROM Table2 WHERE id_aff = '.$user_bro['id_aff'].' AND ref = '.$income['id_user'];

顺便说一下,你不应该使用 mysql _ * 函数,因为它们已被弃用

答案 1 :(得分:0)

您可以加入两个表,例如

$query = 'SELECT * FROM Table1
         JOIN table Table2 
         ON Table2.id_aff = Table1.id_aff AND Table2.ref = Table1.id_user  
         WHERE id_ref = '.$id_user.' AND active = 1 AND approved = 1 
         ORDER BY `id_aff` DESC';

以及更多关于第二个选择查询的语法错误,请尝试将其替换为

$query = 'SELECT * FROM Table2 
          WHERE id_aff = '.$user_bro['id_aff'].' 
          AND ref = '.$income['id_user'];