简体   繁体   English

MySql仅从父键具有多个值的子表中获取记录

[英]MySql Get records only from child table where the parent key has multiple values

I have 2 tables parent and child. 我有2张桌子父母和孩子。 Parent has a field called unique_id and child has a field called parent_unique_id and it is the foreign key in the child table. 父级有一个名为unique_id的字段,子级有一个名为parent_unique_id的字段,它是子表中的外键。 Parent table has 4 records for the same unique_id and child table has 5 records for the same unique_id. 父表具有4条记录,用于相同的unique_id,子表具有5条记录,用于相同的unique_id。

When I join them to get the records, I am getting a total of 20 records each 5 records of the child table are repeating 4 times. 当我加入它们以获取记录时,我总共得到20条记录,子表的每5条记录重复4次。

The query I am using is 我正在使用的查询是

SELECT c.* FROM child c JOIN parent p ON c.parent_unique_id = p.unique_id

I tried LEFT JOIN as well but I am still getting 20 records which are repeated. 我也尝试了LEFT JOIN,但是我仍然得到20条重复记录。

One method is to use IN or EXISTS : 一种方法是使用INEXISTS

SELECT c.*
FROM child c 
WHERE c.parent_unique_id IN (SELECT p.unique_id FROM parent p);

Of course, you could just slap SELECT DISTINCT on your query. 当然,您可以在查询中拍“ SELECT DISTINCT ”。 However, that requires and unnecessary processing. 但是,这需要不必要的处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MySQL仅在子表中的记录与另一个子表中的记录匹配时才从父表中选择行 - MySQL select rows from parent table only if records in child table match records in another child table MySQL的:从父表中选择,只有当子表有行 - Mysql: Select from parent table, only if child table has rows 仅当子表中的外键在父表中具有分配给它的值时,才在子表中创建条目 - create entry in child table only if the foreign key from the child table has a value assigned to it in parent table MySQL从父表中查找创建日期在日期之前和之后的子记录 - MySQL find child records where created date is before and after date from parent table 遍历父表中的记录,其中子表中的parentTableID和 - Loop through records from parent table where parentTableID in child table and 从MySQL中的父表和子表中删除记录 - Delete records from parent table and child table in mysql MYSQL Join-父子表连接并仅从子表中获取最新记录 - MYSQL Join - Parent and Child table join and get only the latest record from the child table 从子表中为N个MySQL视图中的每个父记录获取N条记录 - Get N number of records from child table for each parent record in a MySQL View 使用WHERE mysql查询从主表中获取所有记录,并从子表中进行匹配 - Get all records from master table and matching from child using WHERE mysql query MySQL查找在所有子记录中找到给定值的父记录 - Mysql find parent records where given values are found in all child records
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM