如何从 MySQL 中的一个到多个相关表中选择唯一的行?
作为 MySQL-Noob,我正在努力解决以下任务:假设 3 个表:location
groceries
和 person
具有以下属性:
- 每个表都有一个主自动增量整数 id 和一个 varchar 列。
- 表中的条目都是唯一的。
groceries
中的每个条目都有一个person
中条目的外键。- 来自
groceries
的多个条目可能共享相同的外键。 - (3) 和 (4) 也适用于
person
和location
所以我们有一个多对一多的关系。如何选择每个三元组 (groceries_product, person_name, location_name)
,其中 person_name
不会出现多次?
示例:
tables: groceries | person | location
------------------------------------ ------------- -------------------------
columns: id product person_id | id name | id name person_id
------------------------------------ ------------- -------------------------
1 hamburger 1 | 1 Peter | 1 home 1
2 cheeseburger 1 | 2 Tom | 2 work 1
3 carot 1 | | 3 zoo 2
4 potatoe 1 | |
5 mango 2 | |
您可以创建的所有出现 Peter
的三元组都是无关紧要的。我只想要像(芒果,汤姆,动物园)这样的三元组,因为汤姆在所有可能性中只出现一次。我希望我的问题可以理解。 :-)
As MySQL-Noob I am struggeling to solve the following task: Assuming 3 tables: location
groceries
and person
with the following properties:
- Every table has a primary autoincremented integer id and a varchar column.
- The entrys in the tables are all unique.
- Every entry in
groceries
has a foreign key of an entry inperson
. - It is possible that more then one entry from
groceries
share the same foreign key. - (3) and (4) apply to
person
andlocation
, too
So we have a many to one to many relation. How can I select every triple (groceries_product, person_name, location_name)
where person_name
does not occur more then once?
Example:
tables: groceries | person | location
------------------------------------ ------------- -------------------------
columns: id product person_id | id name | id name person_id
------------------------------------ ------------- -------------------------
1 hamburger 1 | 1 Peter | 1 home 1
2 cheeseburger 1 | 2 Tom | 2 work 1
3 carot 1 | | 3 zoo 2
4 potatoe 1 | |
5 mango 2 | |
All the triples you can create in which Peter
occures are irrelevant. I want only triples like (mango, Tom, zoo), because Tom does occure only once in all possibilities. I hope my question ist understandable. :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你必须进行子选择才能得到结果:
I think you have to do a subselect to get your result: