家庭表
familynumber fistname lastname 10001 A B 10002 C D 10003 E F 10004 G H
电话表
familynumber phonenumber description 10001 111 mobile 10001 222 home 10001 333 text 10002 444 text 10003 555 work 10003 666 mobile
我需要输出
familynumber phonenumbers 10001 111, 222, 333 10002 444 10003 555, 666
我知道可以通过以下代码来完成
$families = mysql_query("select * from family")
while($family = mysql_fetch_assoc($families))
{
extract($family);
echo "<td>$familynumber</td>";
echo "<td>";
$phones = mysql_query("select * from phone where familynumber = '$familynumber'");
while($phone = mysql_fetch_assoc($phones))
{
extract($phone);
echo $phonenumber . ", ";
}
echo "</td>";
}
但是我需要在一个sql查询中输出这个输出。
答案 0 :(得分:2)
使用GROUP_CONCAT函数
SELECT p.familynumber,
GROUP_CONCAT(DISTINCT p.phonenumber ORDER BY p.phonenumber SEPARATOR ",")
AS phonenumbers
FROM phone p LEFT JOIN family f ON p.familynumber = f.familynumber
GROUP BY familynumber
答案 1 :(得分:0)
SELECT f.familynumber, GROUP_CONCAT(p.phonenumbers) AS numbers
FROM familytable f, phonetable p
WHERE f.familynumber = p.familynumber
GROUP BY familynumber
答案 2 :(得分:0)
好吧,你总是可以使用左连接。那可能就是你要找的东西
就像是:
SELECT * FROM family LEFT JOIN phone ON family.familynumber=phone.familynumber
注意:这将为每个电话号码类型返回一整行(因此,如果一个家庭有3个电话号码,它将返回家庭信息3次)。
有关左连接的更多内容:http://www.tizag.com/mysqlTutorial/mysqlleftjoin.php
注意,还有Right连接和Inner连接。你应该学习并记住这些,它们是可有可无的。当你对它们做得更好时,查找优化连接。有一些很棒的文章可以为你节省宝贵的时间。
答案 3 :(得分:0)
SELECT familynumber,phonenumbers FROM family AS fml INNER JOIN phone AS ph ON fml.familynumber = ph.familynumber GROUP BY ph.familynumber
我不确定,但这可以帮助你或让你处于更好的位置