我正在运行以下查询并使用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. 成长 - 8.9
等。
如果我每列只找到一个结果,这就可以正常工作。
但问题是,我们可以为某些"歌曲"提供多个作者,如下所示(当 ID = 13 时)。
因此,当我们运行查询时,我们会收到一条消息,指出 table03 中的作者有多个值,并且根本没有显示任何内容。
我怎样才能设法拥有一个表格,为我提供多个作者的本列的结果?
ID - 作者---注释--------------------------日期----------标题
01 - 07/01/2013 - 谢谢你的帮助 - 某人 - 8.3
07 - 07/03/2013 - 不客气 - 尼斯先生 - 7.6
11 - 09/27/2013 - 希望你喜欢我们 - J. 成长 - 8.9
13 - 11/14/2013 - 休斯顿,我们有一个问题 - B. Lee & T. Hanks - 6.4
17 - 12/09/2013 - 现在我们只有一个 - P. 诺伊尔 - 7.1
非常感谢!
一种选择是在作者子查询中使用MySQL的GROUP_CONCAT()
。
对于您的情况,您的子查询可能如下所示:
(select
GROUP_CONCAT(a.author)
from
table03 a
where
p.family = a.family) authors
注意:
组中值之间的默认分隔符是逗号 (",")
在子查询中使用 LIMIT(和 ORDER BY)chausule 或在子查询中使用 GROUP_CONCAT() 分组函数。
限制 => https://dev.mysql.com/doc/refman/5.5/en/select.html
GROUP_CONCAT => http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat