查询链接表

时间:2014-11-04 09:32:19

标签: php mysql

请帮我查询一下,我已经玩了一段时间并且无法获得所需的结果。

以下是我的示例数据库的转储:PHPMyAdmin SQL Dump

我希望得到的结果如下:

Array
(
[1] => Array
    (
        [0] => Array
            (
                [id] => 1
                [r_id] => 1
                [u_id] => 1
                [e_id] => 1
                [r] => r1
                [username] => john
            )

        [1] => Array
            (
                [id] => 1
                [r_id] => 1
                [u_id] => 2
                [e_id] => 1
                [r] => r1
                [username] => mark
            )

        [2] => Array
            (
                [id] => 1
                [r_id] => 1
                [u_id] => 3
                [e_id] => 1
                [r] => r1
                [username] => andrew
            )

    )

[2] => Array
    (
        [0] => Array
            (
                [id] => 2
                [r_id] => 
                [u_id] => 
                [e_id] => 1
                [r] => r2
            )

    )
)

这是我可以提出的最接近的查询:My PHP code

2 个答案:

答案 0 :(得分:0)

尝试在查询中使用内部联接

SELECT 
  tb1.*, tb2.e, tb3.e_id, tb3.r, tb4.r_id, tb4.u_id
FROM 
  tb1
INNER JOIN 
  tb2 ON tb1.id = tb2.id
INNER JOIN
  tb3 ON tb1.id = tb3.id
INNER JOIN
  tb4 ON tb1.id = tb4.id

编辑查询后编辑

$sack[$rowId][] = $row;

$sack[] = $row; 

$sack[$rowId] = $row;

答案 1 :(得分:0)

@GusDB你在TB3开始的提示是关键,所以这就是答案

select * from tb3 
    left join tb4 on tb3.id=tb4.r_id
    left join tb1 on tb4.u_id=tb1.id

PHP代码

<?php

$sql = mysqli_query($con, '
            select * from tb3 
                left join tb4 on tb3.id=tb4.r_id
                left join tb1 on tb4.u_id=tb1.id
');

if (!$sql) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

$sack = Array();
while($row = mysqli_fetch_assoc($sql)) {
   $sack[$row['r_id']][] = $row;
}

echo "<pre>";
print_r($sack);
echo "</pre>";

?>