[英]mysql fetch records with foreign records having certain values
I have two tables 我有两张桌子
Parent:
+--+---------+
|id| text |
+--+---------+
| 1| Blah |
| 2| Blah2 |
| 3| Blah3 |
+--+---------+
Children
+--+---------+---------+
|id|parent_id| table_id|
+--+---------+---------+
| 1| 1 | 1 |
| 2| 1 | 3 |
| 3| 2 | 2 |
+--+---------+---------+
I want to find parent having children with table_id both 1 and 3. Currently I am using following query 我想找到有table_id分别为1和3的孩子的父母。目前,我正在使用以下查询
SELECT *
FROM Parent
WHERE id
IN (
SELECT parent_id
FROM Children
WHERE table_id = 1
)
AND id
IN (
SELECT parent_id
FROM Children
WHERE table_id = 3
)
As I have thousands of records, this query runs very slow. 由于我有成千上万的记录,因此该查询运行非常缓慢。
Is there altenative faster query to execute it? 是否有替代性更快的查询来执行它?
You can let mysql EXPLAIN its execution plan to you: check this chapter in the manual. 你可以让MySQL的解释其执行计划你:检查本章的说明书中无。 From there, you can optimize your query for speed.
从那里,您可以优化查询的速度。 There are different approaches to that, it's a broad field - but in general, it's a good start to minimize the number and the width of the included joins and inner queries.
有很多不同的方法,这是一个广阔的领域-但总的来说,这是一个最小化包含的联接和内部查询的数量和宽度的良好起点。
There are many ways of doing it, and one way with proper indexing would make it pretty fast as 有很多方法可以做到,而正确索引的一种方法将使其变得非常快
select p.* from parent p
join children c on c.parent_id = p.id
where c.table_id = 1
and exists (
select 1 from children c1
where c1.parent_id = c.parent_id
and c1.table_id = 3
);
The indexes that could be added as 可以添加为的索引
alter table parent add index id_idx(id);
alter table children add index parent_idx(parent_id);
alter table children add index table_id_idx(table_id);
SELECT c.parent_id, p.text,
SUM(CASE WHEN c.table_id=1 THEN 1 ELSE 0 END) as t_1,
SUM(CASE WHEN c.table_id=3 THEN 1 ELSE 0 END) as t_3
FROM Children c
LEFT JOIN Parent p
ON c.parent_id = p.id
WHERE c.table_id IN ( 1, 3)
GROUP BY c.parent_id
HAVING t_1>0 AND t_3>0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.