MySQL:筛选子记录,包括所有同级记录

MySQL:筛选子记录,包括所有同级记录,mysql,sql,filtering,inner-join,query-optimization,Mysql,Sql,Filtering,Inner Join,Query Optimization,有两个MySQL表: tparent(id int, some data...) tchild(id int, parent_id int, some data...) 我需要返回所有列parent加上所有children,其中至少有一个children符合某些条件 我当前的解决方案: -- prepare sample data DROP TABLE IF EXISTS tparent; DROP TABLE IF EXISTS tchild; CREATE TABLE tparent (

有两个MySQL表:

tparent(id int, some data...)
tchild(id int, parent_id int, some data...)
我需要返回所有列parent加上所有children,其中至少有一个children符合某些条件

我当前的解决方案:

-- prepare sample data
DROP TABLE IF EXISTS tparent;
DROP TABLE IF EXISTS tchild;

CREATE TABLE tparent (id int, c1 varchar(10), c2 date, c3 float);
CREATE TABLE tchild(id int, parent_id int, c4 float, c5 varchar(20), c6 date);
CREATE UNIQUE INDEX tparent_id_IDX USING BTREE ON tparent (id);
CREATE UNIQUE INDEX tchild_id_IDX USING BTREE ON tchild (id);

INSERT INTO tparent 
VALUES
  (1, 'a', '2021-01-01', 1.23)
, (2, 'b', '2021-02-01', 1.32)
, (3, 'c', '2021-01-03', 2.31);

INSERT INTO tchild
VALUES
  (10, 1, 22.333, 'argh1', '2000-01-01')
, (20, 1, 33.222, 'argh2', '2000-01-02')
, (30, 1, 44.555, 'argh3', '2000-02-02')
, (40, 2, 33.222, 'argh4', '2000-03-02')
, (50, 3, 33.222, 'argh5', '2000-04-02')
, (60, 3, 33.222, 'argh6', '2000-05-02');


-- the query
WITH parent_filter AS
(
SELECT
    parent_id
FROM
    tchild
WHERE
    c4>44
)
SELECT
    p.*,
    c.*
FROM
    tparent p
JOIN tchild c ON p.id = c.parent_id
JOIN parent_filter pf ON p.id = pf.parent_id;
它为父id 1和子id 10、20、30返回3行,因为子id 30具有匹配的记录。它不会返回任何其他父id的数据

然而,我在这里查询tchild两次,首先是在CTE中,然后是在主查询中。由于这两个表都是相对较大的10-100百万行,平均每个父记录有2-5个子记录,所以我遇到了性能/时间问题


是否有更好的方法实现此过滤?也就是说,无需多次查询tchild表?

也许您可以使用以下方法:

选择p.*,c* 来自tparent p 加入tchild c 在p.id=c.parent\u id上 存在位置从tchild where中选择1
当子表中至少有一条记录符合条件时,此操作应检索父联接和子联接的所有行。

是否尝试过此版本

SELECT *
FROM tparent p
JOIN tchild c ON p.id = c.parent_id AND <criteria>

通过这种方式,您可以在实际连接之前使用createria限制tchild表

请提供一个并阅读公平点,问题现在已更新为可复制示例它不会返回任何其他父级,因为只有30个表的c4>40正是,这是我需要的。我需要包括至少一个子记录符合条件的所有父记录。这将筛选出父记录的其他子记录。我需要包括父母的所有子记录,而不仅仅是匹配的记录。