我的数据库中有2个关系表。
我一直想把头转到下面。
我有联系表,我有一张订单表。
我想尝试显示联系信息(姓名,电子邮件等)一次,然后显示订单信息。
我知道我可以这样做:
<?php
$query = $db->prepare("SELECT *
FROM contact
WHERE type = ?
ORDER BY date")
or die(mysqli_error($db));
$type = "order";
$query->bind_param('s', $type);
$query->execute();
$query->store_result();
$query->bind_result($id, $name, $email, $date);
while ($query->fetch()) {
$date = strtotime($date);
$date = date("F jS Y", $date);
?>
From: <?php echo $name ?>
<input type="Checkbox" name="checkbox[]" id="checkbox[]"value="<? echo $contactid; ?>">
<p>
<?php
echo $comments
?>
</p>
<?php
echo $date ;
?>
<?php
$order = $db->prepare("SELECT title, number
FROM preorder
WHERE id = ? ")
or die(mysqli_error($db));
$order->bind_param('s', $id);
$order->execute();
$order->store_result();
$order->bind_result( $title, $number );
while ($order->fetch()) {
echo $title, $number ;
}
}
?>
这样做很好,但感觉不对,更简单的方法是不做2选择。我想在那个循环中显示订单,因此每个订单都不会重复名称,电子邮件等。
答案 0 :(得分:1)
我会用这样的left join
来解决它:
<?php
$query = $db->prepare(
"SELECT *, preorder.title, preorder.number " .
"FROM contact " .
"LEFT JOIN preorder ON (contact.contactid = preorder.contactid) " .
"WHERE type = ? ORDER BY contactid, date")
or die(mysqli_error($db));
$type = "order";
$query->bind_param('s', $type);
$query->execute();
$query->store_result();
$query->bind_result($id, $name, $email, $date, $title, $number);
$last_id = false;
while ($query->fetch()) {
$date = strtotime($date);
$date = date("F jS Y", $date);
if ($contactid != $last_id) {
?>
From: <?php echo $name ?>
<input type="Checkbox" name="checkbox[]"
id="checkbox[]" value="<? echo $contactid; ?>">
<p>
<?php
echo $comments
?>
</p>
<?php
echo $date;
}
echo $title, $number;
$last_id = $contactid;
}
?>