[英]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
: 一种方法是使用
IN
或EXISTS
:
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.