MySql Select查询(JOIN上限制选择)
我有 2 个表:tbl_customers
和 tbl_customers_notes
我在表行中显示所有客户(就像一个表一样),并且我想添加一列显示相关 tbl_customers_notes
表中最后一个已知的datetime
记录。
显然,这是一个一对多的关系,其中匹配的recID将是customerid
。
这是我到目前为止所得到的:
<?php
$result = mysql_query("SELECT `customername` FROM `tbl_customers` ");
while($row = mysql_fetch_array( $result )) {
?>
<tr>
<td><?php echo $customername;?></td>
<td><?php echo 'note datetime'; ?></td>
</tr>
<? } ?>
如果我与注释表进行 JOIN 操作,我会得到重复项。我可以限制 tbl_customers_notes
仅选择该 customerid 的最后一条已知记录吗?
I have a 2 tables: tbl_customers
, and tbl_customers_notes
I'm displaying all my customers in table rows (as one does), and I want to add a column that is for displaying the last known datetime
record in the related tbl_customers_notes
table.
Obviously this is a one-to-many relationship where the matching recID is going to be customerid
.
Here is what I have so far:
<?php
$result = mysql_query("SELECT `customername` FROM `tbl_customers` ");
while($row = mysql_fetch_array( $result )) {
?>
<tr>
<td><?php echo $customername;?></td>
<td><?php echo 'note datetime'; ?></td>
</tr>
<? } ?>
If I do a JOIN with the notes table I get duplicates. Can I limit the tbl_customers_notes
to just select the last known record for that customerid?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
按 customerid 和 customername 进行分组的原因是,以防相同的 customername 可能有不同的 customerid。外连接是包含没有备注的客户。
Try this:
The reason for grouping by both customerid and customername is that in case same customername could have different customerids. Outer join is to include customers that have no notes.
我认为
HAVING
是合适的。I think a
HAVING
is in order.