How to select unique rows from one to many relationed tables in MySQL?

别等时光非礼了梦想. 提交于 2019-12-11 17:56:54

问题


As MySQL-Noob I am struggeling to solve the following task: Assuming 3 tables: location groceries and person with the following properties:

  1. Every table has a primary autoincremented integer id and a varchar column.
  2. The entrys in the tables are all unique.
  3. Every entry in groceries has a foreign key of an entry in person.
  4. It is possible that more then one entry from groceries share the same foreign key.
  5. (3) and (4) apply to person and location, 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. :-)


回答1:


I think you have to do a subselect to get your result:

SELECT groceries.product, person.name, location.name
FROM person
LEFT JOIN groceries ON person.id = groceries.person_id
LEFT JOIN location ON person.id = location.person_id
WHERE person.id
IN (
SELECT person.id
FROM person
LEFT JOIN groceries ON person.id = groceries.person_id
LEFT JOIN location ON person.id = location.person_id
GROUP BY person.id
HAVING count( person.id ) =1
)



回答2:


select l.name, m.name, r.name
from `left` l
left join middle m on m.id = l.middle_id
left join `right` r on m.id = r.middle_id;


来源:https://stackoverflow.com/questions/6922675/how-to-select-unique-rows-from-one-to-many-relationed-tables-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!