从2个不同的表中选择值,并在具有相同ID的行中打印值

时间:2016-03-23 12:39:03

标签: php mysql sql

我有这个数据库

表“ADS”

ID   |   Visible
-----------------
15   |      1
16   |      1
17   |      1

表“IMAGES_ADS”

ID    |    NAME    |   ID_ADS
------------------------------
100   |  xlasd.jpg |    15
101   |  dadsa.jpg |    15
102   |  dsfsf.jpg |    16
103   |  ghdfd.jpg |    17
104   |  jkyhg.jpg |    17
105   |  rerem.jpg |    17

现在我想创建一个从这2个表中获取值的php页面,并按id打印ADS列表,其中一行图像名称与以逗号分隔的ADS ID相关。

我写了这段代码

<?php
//ENTER YOUR DATABASE CONNECTION INFO BELOW:
$servername = "localhost";
$username = "user";
$password = "xxxxxx";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    echo 'CONNECT TO DB';
}

$sql = "SELECT ADS.ID, IMAGES_ADS.NAME FROM ADS INNER JOIN IMAGES_ADS ON ADS.ID=IMAGES_ADS.ID_ADS WHERE ADS.Visible=1 ORDER BY ID ASC";
$results = $conn->query($sql);

echo '<table>';

if($results->num_rows > 0) {
    while($row = $results->fetch_assoc()) {
        echo '<tr>
                <td>'.$row["ID"].'</td>
                <td>'.$row["NAME"].'</td>
              </tr>';
    }
} else {
    echo '0 rows';
}
echo '</table>';

$conn->close();
?>

但是使用这段代码我得到了这个结果:

15  xlasd.jpg
15  dadsa.jpg
16  dsfsf.jpg
17  ghdfd.jpg
17  jkyhg.jpg
17  rerem.jpg

但我需要这样的结果:

15  xlasd.jpg, dadsa.jpg
16  dsfsf.jpg
17  ghdfd.jpg, jkyhg.jpg, rerem.jpg

我怎么能得到这个结果?

感谢@Vipin Jain,我写下了以下解决方案:

<?php
//ENTER YOUR DATABASE CONNECTION INFO BELOW:
$servername = "localhost";
$username = "user";
$password = "xxxxxx";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    echo 'CONNECT TO DB';
}

$sql = "SELECT ADS.ID, GROUP_CONCAT(IMAGES_ADS.NAME SEPARATOR', ') as b
        FROM ADS INNER JOIN IMAGES_ADS
        ON ADS.ID=IMAGES_ADS.ID_ADS
        WHERE ADS.Visible=1
        ORDER BY ID ASC";

$results = $conn->query($sql);

echo '<table>';

if($results->num_rows > 0) {
    while($row = $results->fetch_assoc()) {
        echo '<tr>
                <td>'.$row["ID"].'</td>
                <td>'.$row["b"].'</td>
              </tr>';
    }
} else {
    echo '0 rows';
}
echo '</table>';

$conn->close();
?>

3 个答案:

答案 0 :(得分:4)

您应该使用GROUP_CONCAT

SELECT ADS.ID, GROUP_CONCAT(IMAGES_ADS.NAME)
FROM ADS 
INNER JOIN IMAGES_ADS 
ON ADS.ID=IMAGES_ADS.ID_ADS 
WHERE ADS.Visible=1 
GROUP BY ID 
ORDER BY ID ASC;

答案 1 :(得分:1)

您可以通过以下查询 -

SELECT a.ID, GROUP_CONCAT(b.NAME)
FROM ADS as a
INNER JOIN IMAGES_ADS as b
ON a.ID=b.ID_ADS 
WHERE ADS.Visible=1 
Group by a.ID;

答案 2 :(得分:0)

$res = [];    
while($row = $results->fetch_assoc()) {
    if (empty($res[$row["ID"]])) {
        $res[$row["ID"]] = [$row];
    } else {
        $res[$row["ID"]][] = $row;
    }
}

您将获得按ID分组的行数组