0

我有一个嵌套列表,它将显示客户及其电话号码,如下所示:

杰森

555 111-1111
555 222-2222

克里斯汀

555 333-3333

约翰

555 444-4444
555 555-5555
555 656-6666

不过,我无法添加他们的电子邮件。此代码只是复制每个电话号码下的电子邮件,但我需要将电话号码和电子邮件分组在每个客户下,例如:

杰森

555 111-1111
555 222-2222
jason@jason.com
jason.alternative@jason.com 

克里斯汀

555 333-3333
kristen@kristen.com
kristen.alternative@kristen.com
kristen.personal@kristen.com

约翰

555 444-4444
555 555-5555
555 656-6666
john@john.com

PHP代码:

<?php
$result = mysqli_query($dbc,"
SELECT 
fname, 
phone, 
email
FROM 
customer, 
phone, 
email, 
customer_phone, 
customer_email
WHERE
customer.id=customer_phone.customer_id
AND
phone.id=customer_phone.phone_id
AND
customer.id=customer_email.customer_id
AND
email.id=customer_email.email_id
order by fname
");

$oldname = null;
while($row = mysqli_fetch_array($result))
{
    if($oldname != $row['fname'])
    {
        echo "<h3>".$row['fname']."</h3>";
        $oldname = $row['fname'];
    }
    echo "<p>".$row['phone']."</p>";
    echo "<p>".$row['email']."</p>";
}
?>
4

1 回答 1

1

此查询将通过首先获取电话号码和第二个电子邮件来将电子邮件插入电话号码之后。带有“1-Phone”和“2-Email”的列确保电子邮件在电话号码之后排序。

SELECT fname, '1-Phone' AS InfoType, phone AS TheInfo
  FROM Customer
  INNER JOIN phone ON phone.id=customer_phone.phone_id
  INNER JOIN customer_phone ON customer.id=customer_phone.customer_id
UNION SELECT fname, '2-Email', email
  FROM Customer
  INNER JOIN email ON email.id=customer_email.email_id
  INNER JOIN customer_email ON customer.id=customer_email.customer_id
ORDER BY fname, InfoType

我将连接更改为 ANSI 语法,因为它使我更容易处理它;没有其他原因。如果这是您的偏好,请随意将连接条件推回WHERE子句 - 我对此感觉不强烈:)

对渲染代码的唯一更改是替换这个......

echo "<p>".$row['phone']."</p>";
echo "<p>".$row['email']."</p>";

... 有了这个:

echo "<p>".$row['TheInfo']."</p>";
于 2013-03-22T03:42:01.483 回答