简体   繁体   English

用另一个表中的名称替换拉出的SQL ID值

[英]Replacing a pulled SQL ID value with its name from another table

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. 但是,我希望将为site_id显示的ID替换为存储在另一个表中的实际名称。 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. 例如, site_id是名为sites_tbl的表中的主键,我想拉出关联的sitename并将其显示在表中,而不是作为外键来自sheets_tbl的ID。 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. 我假设我需要做一些循环,其中foreach site_id在$ data变量中选择sitename Where site_id = the $row['site_id']但是我无法让它工作。

$sql  = "SELECT * FROM sheet_tbl";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();


  <?php foreach ($data as $row): ?>
    <tr>
        <td><?=$row['sheet_id']?></td>
        <td><?=$row['username']?></td>
        <td><?=$row['site_id']?></td>
   </tr>

I would advise a very simple SQL join. 我建议一个非常简单的SQL连接。 Assuming the site name is sitename in the sites_tbl: 假设站点名称在sites_tbl中是sitename

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


  <?php foreach ($data as $row): ?>
    <tr>
        <td><?=$row['sheet_id']?></td>
        <td><?=$row['username']?></td>
        <td><?=$row['sitename']?></td>
   </tr>

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. 所以现在你不仅拥有来自sheet_tbl的数据,还sites_tbl你现在可以直接使用的sites_tbl的相关数据。

Read more about joins here: http://www.w3schools.com/sql/sql_join.asp 阅读更多关于联接的信息: http//www.w3schools.com/sql/sql_join.asp

You can join the tables together; 您可以join表一起;

select  sheet.sheet_id
,       sheet.username
,       site.sitename
from    sheet_tbl sheet
join    sites_tbl site
on      sheet.site_id = site.site_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM