MySQL同表关联的id替换名称,用另一个表中的名称替换已拉取的SQL ID值

I have some code (see below) that populates a table with all the records. I however want to replace the ID that is presented for site_id with its actual name which is stored in another table. The site_id for example is the primary key in a table called sites_tbl, and I want to pull the associated sitename and display this in the table rather than the ID which comes from the sheets_tbl as a foreign key. I assume I need to do some kind of loop, where foreach site_id within the $data variable Select the sitename Where site_id = the $row['site_id'] However I cannot get it to work.

$sql = "SELECT * FROM sheet_tbl";

$stmt = $conn->prepare($sql);

$stmt->execute();

$data = $stmt->fetchAll();

=$row['sheet_id']?>=$row['username']?>=$row['site_id']?>

解决方案

I would advise a very simple SQL join. Assuming the site name is sitename in the sites_tbl:

$sql = "SELECT sheet.sheet_id, sheet.username, site.sitename FROM sheet_tbl S

JOIN sites_tbl ST ON ST.site_id = S.site_id ";

$stmt = $conn->prepare($sql);

$stmt->execute();

$data = $stmt->fetchAll();

=$row['sheet_id']?>=$row['username']?>=$row['sitename']?>

So now you not only have the data from sheet_tbl but also the associated data from sites_tbl that you can now use directly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值