dongxinche1264 2017-08-21 23:28
浏览 23
已采纳

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

I need to select data from one MySQL table and match an ID from the query to get an email address from the second table. Then output the results. My current code is:

$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);
}

I would like to incorporate in this query:

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

And output the results:

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

1条回答 默认 最新

  • dsvf46980 2017-08-21 23:30
    关注

    You can use a join. Use an outer join if the second table's record may not be present:

    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
    

    The outer join selects records that match the ON clause, but those fields will be null if there is no matching record for the parent table (osei_t_payment_pro_wallet).

    Updated output (from OP):

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

    Though I would write this:

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

    You could also use the results directly:

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

    $cash still needs to be calculated.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)