我有这个数据库
表格“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
现在我想创建一个 php 页面,从这 2 个表中获取值,并按 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();
?>
最佳答案
你应该使用 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;
关于php - 从 2 个不同的表中选择值并在具有相同 ID 的一行中打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36178439/