一对多mysql查询

发布于 2024-12-26 05:20:26 字数 518 浏览 2 评论 0原文

嘿伙计们,很抱歉问这个问题,但我需要有关此查询的帮助,我一直在尝试不同的解决方案,但到目前为止还无法自己解决。

我有 4 个表,分别为 customerfiguresnoteslender。它们都有一个名为 reference 的字段,我用它来将它们链接在一起。客户是主表,每个客户的数字表中只有一条记录,因此我可以这样做:

select * From customer, figures
where customer.reference = figures.reference

但是,每个客户可能有多个票据和贷方记录。我如何链接它们以仅显示一条记录?

理想情况下,有一种方法可以将其显示为:

reference, name, figures, lender 1, lender 2, note 1, note 2, note 3

Hey guys sorry to ask but i need help with this query please I've been messing around with different solutions but so far have not been able to solve it myself.

I have 4 tables called customer, figures, notes and lender. They all have a field called reference, which is what I'm using to link them together. Customer is the primary table and there is only one record in the figures table for each customer so i can do:

select * From customer, figures
where customer.reference = figures.reference

However, there may be multiple notes and lender records for each customer. How can I link them to show only one record?

Ideally, there would be a way to display it as:

reference, name, figures, lender 1, lender 2, note 1, note 2, note 3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紫瑟鸿黎 2025-01-02 05:20:26

您可以使用 group_concat()

SELECT customer.reference, customer.name, figures.name, 
GROUP_CONCAT(DISTINCT lender.name), 
GROUP_CONCAT(DISTINCT notes.name) 
FROM customer 
JOIN figures ON figures.reference = customer.reference 
LEFT JOIN lender ON lender.reference = customer.reference 
LEFT JOIN notes ON notes.reference = customer.reference 
GROUP BY customer.reference;

假设每个表都有一个字段name,您应该将其更改为您的列。

You can use group_concat():

SELECT customer.reference, customer.name, figures.name, 
GROUP_CONCAT(DISTINCT lender.name), 
GROUP_CONCAT(DISTINCT notes.name) 
FROM customer 
JOIN figures ON figures.reference = customer.reference 
LEFT JOIN lender ON lender.reference = customer.reference 
LEFT JOIN notes ON notes.reference = customer.reference 
GROUP BY customer.reference;

Assuming that each of the tables has a field name, you should change it to whatever your columns are.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文