PHP MySQL从2个表中获取数据 [英] PHP MySQL get data from 2 tables

查看:81
本文介绍了PHP MySQL从2个表中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并数据库中的2个表:

I am trying to combine 2 tables from my database:

文件表:

    id
    file_name
    file_description
    file_url

access_files表:

access_files table:

    id
    student_id
    file_id

这是我的sql代码,当前从文件表中获取所有文件,它不会为用户显示所选文件.

Here is my sql code, currently getting all files from the files table, it doesn`t show the selected files for the user.

<?php
    $SQL = "SELECT * FROM files, access_files WHERE student_id ='$studentid'";
    $result = mysql_query($SQL);

    while ($db_field = mysql_fetch_assoc($result)) {
?>                          

<div class="accordion-group">
<div class="accordion-heading">
    <a href="#<?php print $db_field['file_id']; ?>" data-parent="#accordion" data-toggle="collapse" class="accordion-toggle collapsed">
    <?php print $db_field['file_name']; ?>
    </a>
</div>
<div class="accordion-body collapse in" id="<?php print $db_field['file_id']; ?>">
    <div class="accordion-inner">
    <?php print $db_field['file_description']; ?><br/><br/>
    <a href="?download=<?php print $db_field['file_url']; ?>" class="more">Download File Now!</a>
    <br/><br/>
    </div>
</div>
</div>
<?php } ?>

该代码假定仅显示与用户关联的文件.

The code is suppose to show only the files associated to the user.

推荐答案

您需要做的就是联接表.

What you need to do is JOIN the tables.

最常见的JOIN类型:

  1. INNER JOIN-用于匹配可以匹配ON()语句的数据.如果ON()不匹配,则结果将被排除.
  2. 左联接-如果不需要在ON()中匹配的数据,则使用该联接.它只是将数据附加到原始FROM,然后在没有数据匹配的情况下用NULL填充列.

示例

SELECT
 ft.id,
 ft.file_name,
 ft.file_description,
 ft.file_url,
 af.id as access_id,
 af.student_id,
 af.file_id
FROM
 files ft
 INNER JOIN access_files af ON ( ft.id = af.file_id )
WHERE
 fa.student_id = '$studentid'

这篇关于PHP MySQL从2个表中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆