将一行连接到另一个表中的多行
我有一张实体(我们称其为“人”)和属性(一个人可以拥有任意数量的属性)的表。例如:
人员
Name Age
--------
Jane 27
Joe 36
Jim 16
属性
Name Property
-----------------
Jane Smart
Jane Funny
Jane Good-looking
Joe Smart
Joe Workaholic
Jim Funny
Jim Young
我想编写一个有效的选择,根据年龄选择人员并返回他们的全部或部分属性。
Ex: People older than 26
Name Properties
Jane Smart, Funny, Good-looking
Joe Smart, Workaholic
返回其中一项属性和总属性数也是可以接受的。
查询应该是高效的:人员表中有数百万行,属性表中有数十万行(因此大多数人没有属性)。一次选择数百行。
有什么办法可以做到吗?
I have a table to entities (lets call them people) and properties (one person can have an arbitrary number of properties). Ex:
People
Name Age
--------
Jane 27
Joe 36
Jim 16
Properties
Name Property
-----------------
Jane Smart
Jane Funny
Jane Good-looking
Joe Smart
Joe Workaholic
Jim Funny
Jim Young
I would like to write an efficient select that would select people based on age and return all or some of their properties.
Ex: People older than 26
Name Properties
Jane Smart, Funny, Good-looking
Joe Smart, Workaholic
It's also acceptable to return one of the properties and total property count.
The query should be efficient: there are millions of rows in people table, hundreds of thousands of rows in properties table (so most people have no properties). There are hundreds of rows selected at a time.
Is there any way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用:
您需要 MySQL 函数 GROUP_CONCAT (文档),以便返回 PROPERTIES.property 值的逗号分隔列表。
我使用 LEFT JOIN 而不是 JOIN 来包含在 PROPERTIES 表中没有值的 PEOPLE 记录 - 如果您只想要在 PROPERTIES 表中具有值的人员列表,请使用:
我意识到这是一个示例,但是当您考虑有多少个“John Smith”时,使用名称对于引用完整性来说是一个糟糕的选择。分配一个 user_id 作为每个用户的唯一值将是更好的选择。
Use:
You want the MySQL function GROUP_CONCAT (documentation) in order to return a comma separated list of the PROPERTIES.property value.
I used a LEFT JOIN rather than a JOIN in order to include PEOPLE records that don't have a value in the PROPERTIES table - if you only want a list of people with values in the PROPERTIES table, use:
I realize this is an example, but using a name is a poor choice for referencial integrity when you consider how many "John Smith"s there are. Assigning a user_id, being a unique value per user, would be a better choice.
试试这个
try this
您可以使用 INNER JOIN 将两个表链接在一起。 有关 JOIN 的更多信息。
但是,添加唯一的主键< /a> 到这样的表,并创建一个 索引< /a> 提高速度。
假设表
People
有一个字段id
表
Properties
有一个字段peopleId
将它们链接在一起然后查询将如下所示:
You can use
INNER JOIN
to link the two tables together. More info on JOINs.However, it's often a lot faster to add a unique primary key to tables like these, and to create an index to increase speed.
Say the table
People
has a fieldid
And the table
Properties
has a fieldpeopleId
to link them togetherThen the query would then look something like this: