在MySQL中进行三表连接

时间:2016-09-13 17:31:31

标签: mysql

这是我的表

program_join ('program_join_id, member_ID, program_schedule_id');

program_schedule (program_scedule_id, program_id, datetime');

program ('program_id, program_name);

这是我的mysql

$mySql = "SELECT 
            program_join.program_join_id,
            member.member_username, 
            program_join.program_schedule_id

            FROM program_join

                INNER JOIN member ON
                program_join.member_ID=member.member_ID
                ORDER BY program_join_id";


$myQry = mysql_query($mySql, $DB)  or die ("wrong query : ".mysql_error());
$number = $hal; 
while ($myData = mysql_fetch_row($myQry)) {
    $number++;
    $code = $myData[0];
?>
<tr align="center">
    <td><?php echo $number;?></td>
    <td><?php echo  $myData[1];?></td>
    <td><?php echo  $myData[2];?></td>

结果

No      username      program schedule
1        lalala          1
2        bababba         2

在&#39;节目时间表&#39;下,我想显示我从&#39;的节目名称。 program_join.program_schedule_id&#39;

请帮帮我

2 个答案:

答案 0 :(得分:1)

只需使用联接从程序表中获取program_name:

SELECT 
pj.program_join_id,
m.member_username, 
p.program_name,
ps.datetime

FROM program_join pj
INNER JOIN member m ON pj.member_ID=m.member_ID
INNER JOIN program_schedule ps ON ps.program_schedule_id = pj.program_schedule_id
INNER JOIN program p ON p.program_id = ps.program_id
ORDER BY ... blah blah

答案 1 :(得分:0)

假设还有一个名为program_schedule的表,我将添加一个连接并获取所需的列,下面是示例查询(带有假定的表/列名称):

SELECT 
            program_join.program_join_id,
            member.member_username, 
            program_join.program_schedule_id,
            program_schedule.program_name

            FROM program_join

                INNER JOIN member ON
                program_join.member_ID=member.member_ID
                JOIN program_schedule on program_schedule.id = program_join.program_schedule_id,
                ORDER BY program_join_id ASC LIMIT $hal, $line";