一个查询连接一张表中的多行
好的,我在 MySQL 中有两个表。一张表保存客户信息,另一张表保存电话号码。我需要在一个查询中加入这些表,以从电话表中选择最多两个电话号码以及客户信息。现在我的查询是:
SELECT customers.name, phones.phone, phones2.phone
FROM customers
LEFT JOIN phones ON phones.customerid=customers.id
LEFT JOIN phones AS phones2 ON phones2.customerid=customers.id
GROUP BY customers.id;
但是,这会为电话 1 和电话 2 返回相同的电话号码。本质上我需要做的是将 Phone2 偏移 1,但我不知道如何在语法上做到这一点。
电话位于单独的表中,因为它是一对多的关系。
我需要将其包含在一个查询中,因为我将其直接导出到 csv。
非常感谢您的帮助。提前致谢。
Ok, so I have two tables in MySQL. One table holds customer information, the other holds phone numbers. I need to join these tables in one query to select up to two phone numbers from the phones table as well as customer information. right now my query is:
SELECT customers.name, phones.phone, phones2.phone
FROM customers
LEFT JOIN phones ON phones.customerid=customers.id
LEFT JOIN phones AS phones2 ON phones2.customerid=customers.id
GROUP BY customers.id;
However, this returns the same phone number for phone 1 and phone 2. essentially what I need to do is offset phones2 by 1, but I don't know how to do that syntactically.
The phones are in a separate table because it's a one to many relationship.
I need this to be in one query because I'm exporting this directly to a csv.
Help is much appreciated. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要的是删除数字相同的情况。
What you want is to do remove the cases where the numbers are the same.
那么您只想为每个客户提供任意 0、1 或 2 个电话号码吗?如果是的话
Max
和Min
可以吗?这将为您节省一个加入时间。You just want an arbitrary 0,1, or 2 phone numbers per customer then? If so
Max
andMin
OK? This will save you a join.为了避免两次获得相同的电话号码,您可以更改以下内容:
为此:
To avoid getting the same phone number twice you could change this:
To this: