doujiu8145 2015-05-02 11:33
浏览 90
已采纳

在另一个查询中使用MySQL结果

I have this code which lists everything in tbl_inventory for a given company which works fine:

$result_inventory = mysqli_query($con,"SELECT * FROM tbl_inventory WHERE company_id='$company_id' ORDER BY ip_address")

while($row = mysqli_fetch_array($result_inventory))
echo "<td>{$row['type']} </td>";
echo "<td>{$row['ip_address']} </td>";
echo "<td>{$row['site']} </td>";

The site column gives a number which correlates to an ID in another table which I want to use to run another query such as:

SELECT name FROM tbl_sites WHERE site_id='$site'

However I'm not sure on how to define $site from the previous result

Could someone point me in the right direction?

  • 写回答

2条回答 默认 最新

  • dqf98772 2015-05-02 11:59
    关注

    @Rayblade's answer seems legit, however, you can also perform a JOIN-statement between the two tables:

    SELECT tbl_sites.name FROM tbl_inventory 
    LEFT JOIN tbl_sites ON tbl_inventory.site = tbl_sites.site_id 
    WHERE tbl_inventory.company_id='$company_id' 
    ORDER BY tbl_inventory.ip_address
    

    This will successfully get the tbl_sites.name column, for every company that matches a site. Here you can of course get any arbitrary number of columns, just make sure to use the table name as prefix, since we now have two tables in the query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入