MySQL:限制与具有多个子元素的联接的 FROM 相关的结果
我有一个我从中选择的主表和一个包含我在联接中选择的子元素的表。示例:
person skill person_to_skill
id | name id | skill id | p_id | s_id
------------ ------------ ----------------
1 | jim 1 | sewing 1 | 1 | 2
2 | peter 2 | cooking 2 | 2 | 1
3 | susan 3 | singing 3 | 2 | 3
4 | kevin 4 | 3 | 1
5 | 3 | 2
6 | 4 | 3
现在我们看到,sim 只有一项技能,peter 有两项,依此类推。 现在,如果我从 person、koin Skill 中选择,然后还加入 person_to_skill,但我只想要两个人。我如何在不分组的情况下做到这一点,从而无法获得所有技能?
简而言之:我想从“人”中选择两个具有所有技能的人。
我尝试只使用LIMIT,但这限制了结果行,而不是人员。 如果我使用GROUP BY,我每人只能获得一项技能。 如果没有子选择,这可能吗?
有人有什么想法吗?
到目前为止,我的方法已更改为使用示例,如下所示:
SELECT p.id,p.name,s.skill
FROM person AS p
LEFT JOIN person_to_skill psk ON (psk.p_id = p.id)
LEFT JOIN skill s ON (s.id = psk.s_id)
ORDER BY p.name
LIMIT 0,2
I habe a main table that i select from and a table with subelements that i select from in a join. Example:
person skill person_to_skill
id | name id | skill id | p_id | s_id
------------ ------------ ----------------
1 | jim 1 | sewing 1 | 1 | 2
2 | peter 2 | cooking 2 | 2 | 1
3 | susan 3 | singing 3 | 2 | 3
4 | kevin 4 | 3 | 1
5 | 3 | 2
6 | 4 | 3
So now we see, sim has only one skill, peter has two and so forth.
Now if i select from person, koin skill and then also join person_to_skill, but i only want two persons. How do i manage to do so without grouping and thereby not getting all the skills?
Shortly: I want to select two persons from "person" with all their skills.
I tried just using LIMIT but that limits the result rows, not the persons.
If i use GROUP BY i only get one skill per person.
Is this possible without a subselect?
Any ideas anyone?
My Approach so far, changed to work with the example, looks like this:
SELECT p.id,p.name,s.skill
FROM person AS p
LEFT JOIN person_to_skill psk ON (psk.p_id = p.id)
LEFT JOIN skill s ON (s.id = psk.s_id)
ORDER BY p.name
LIMIT 0,2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在子查询中一开始限制人数,然后像您已经完成的那样加入其他表:
在评论后添加:
如果您确实不能使用子查询,您可以使用两个查询来做到这一点。首先选择用户 ID:
然后在下一个查询中使用这些 ID:
Limit number of persons at very beginning in subquery then join to them other tables as you've already done:
Added after comment:
If you really can't use subqueries you can do it using two queries. Firstly select users ids:
and then use those ids in next query:
您可以执行类似的操作
,然后按人员分组并限制行数。
You can do something like
and then group by person and limit the number of rows.