我正在运行以下查询并使用 php 显示结果:
<?php
$con=mysqli_connect("host","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "select
p.id,
p.date,
(select
t.title
from
table02 t
where
p.family = t.family) title,
(select
a.author
from
table03 a
where
p.family = a.family) author,
(select
n.note
from
table04 n
where
p.family = n.family) note,
from
table01 p
where
p.family in (48766 , 276197, 265242, 334879)";
$result = mysqli_query($con,$query);
echo "<table border='1'><tr><th>ID</th><th>Date</th><th>Title</th><th>Author</th><th>Note</th></tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['author'] . "</td>";
echo "<td>" . $row['note'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
所以我们会有一个这样的表:
ID - 日期 ---------- 标题 -------------------------- 作者 --- 注意
01 - 07/01/2013 - 谢谢你的帮助 - 有些人 - 8.3
07 - 07/03/2013 - 不客气 - 尼斯先生 - 7.6
11 - 09/27/2013 - 希望您喜欢我们 - J. Growth - 8.9
等等
如果我为每一列只找到一个结果,则效果很好。
但问题是,某些“歌曲”可能有多个作者,如下所示(当 ID = 13 时)。
因此,当我们运行查询时,我们会收到一条消息,表明 table03 中的author 有多个值,但根本没有显示任何内容。
我怎样才能设法拥有一个表格,为我提供该专栏的多个作者的结果?
ID - 日期 ---------- 标题 -------------------------- 作者 --- 注意
01 - 07/01/2013 - 谢谢你的帮助 - 有些人 - 8.3
07 - 07/03/2013 - 不客气 - 尼斯先生 - 7.6
11 - 09/27/2013 - 希望您喜欢我们 - J. Growth - 8.9
13 - 11/14/2013 - 休斯顿,我们有一个问题 - B. Lee 和 T. Hanks - 6.4
17 - 12/09/2013 - 现在我们只有一个 - P. Neuer - 7.1
非常感谢!
最佳答案
一种选择是使用 MySQL 的 GROUP_CONCAT()
在您的作者子查询中。
对于您的情况,您的子查询可能如下所示:
(select
GROUP_CONCAT(a.author)
from
table03 a
where
p.family = a.family) authors
注意:
The default separator between values in a group is comma (“,”)
关于php - 如何使用 mysql 和 php 显示查询(带有子查询)的结果,其中一列可以有多个信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22888135/