[英]Mysql: Select from parent table, only if child table has rows
I need your help, How do I Select from a parent table, only if child table (another table that depends on id of parent table) has rows in php? 我需要您的帮助,仅当子表(取决于父表的ID的另一个表)在php中有行时,如何才能从父表中进行选择?
For instance: I have CATEGORY
table and Items
table. 例如:我有
CATEGORY
表和Items
表。 Where Category
is the parent table and contains ct_id, ct_name
, while Items
is child table which contains it_id, ct_id
(linked to parent table), it_name
其中
Category
是父表并包含ct_id, ct_name
,而Items
是包含it_id, ct_id
(链接到父表), it_name
子表
PS: I don't need to select items, but I need only Categories ONLY if there are items linked to this table. PS:我不需要选择项目,但是仅当类别链接到此表时才需要类别。
Thank you 谢谢
You could use INNER JOIN
which only returns records when there is a match on both tables. 您可以使用
INNER JOIN
仅在两个表都匹配时才返回记录。
SELECT DISTINCT a.* FROM Categories a INNER JOIN Items b on b.ct_id = a.ct_id
But it is more efficient to run a subquery: 但是运行子查询效率更高:
SELECT *
FROM Categories
WHERE ct_id IN (SELECT ct_id FROM Items);
This is because in the first example it has to match the entire table first and then strip out all the duplicates using the DISTINCT
keyword. 这是因为在第一个示例中,它必须首先匹配整个表,然后使用
DISTINCT
关键字除去所有重复项。 The second example avoids the duplication by scanning the child table first. 第二个示例通过首先扫描子表来避免重复。
This is known as a Semi Join
. 这称为
Semi Join
。 See here for more: https://dev.mysql.com/doc/refman/5.6/en/semi-joins.html 看到这里更多: https : //dev.mysql.com/doc/refman/5.6/en/semi-joins.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.