从同一语句中的2个MySQL表中选择

时间:2017-08-21 23:28:45

标签: php mysql

我需要从一个MySQL表中选择数据并匹配查询中的ID以从第二个表中获取电子邮件地址。然后输出结果。我目前的代码是:

$sql = "SELECT fk_i_user_id, i_amount FROM osei_t_payment_pro_wallet
        WHERE i_amount > 0 order by i_amount  DESC";

$rows = mysqli_query($conn, $sql);

while ($rs = mysqli_fetch_array($rows, MYSQLI_ASSOC)){
    $uid = $rs["fk_i_user_id"];
    $cash = $rs["i_amount"] / 1000000;
    echo "User ID - ".$uid." Wallet Val - ".$cash.chr(10).chr(13);
}

我想在此查询中加入:

"SELECT s_email FROM osei_t_user where pk_i_id =".$uid;

输出结果:

echo "User ID - ".$uid." Wallet Val - ".$cash." - Email: ".(value from above query).chr(10).chr(13);

1 个答案:

答案 0 :(得分:0)

您可以使用加入。如果第二个表的记录可能不存在,请使用外部联接:

SELECT fk_i_user_id,i_amount, s_email 
FROM osei_t_payment_pro_wallet 
LEFT OUTER JOIN osei_t_user ON pk_i_id=fk_i_user_id
WHERE i_amount > 0 order by i_amount DESC

外连接选择与ON子句匹配的记录,但如果父表没有匹配的记录,则这些字段将为null(osei_t_payment_pro_wallet)。

更新输出(来自OP):

$email = $rs["s_email"]; 
echo "User ID - ".$uid." Wallet Val - ".$cash." Email -".$email.chr(10).chr(13); 

虽然我会这样写:

echo "User ID - {$uid} Wallet Val - {$cash} Email - {$email}\n\r";

您也可以直接使用结果:

echo "User ID - {$rs["fk_i_user_id"]} Wallet Val - {$cash} Email - {$rs["s_email"]}\n\r";

$cash仍然需要计算。