I have table (about 80'000 rows), looks like
id, parentId, col1, col2, col3...
 1,     null, 'A', 'B', 'C'
 2,        1, ...
 3,        1, ...
 4,     null, ...
 5,        4, ...
(one level parent - child only)
and I need get all dependent rows -
SELECT ... 
FROM table 
WHERE id = :id OR parentId = :id OR id IN (
    SELECT parentId 
    FROM table 
    WHERE id = :id
    )
but why this request working slowly instead 2 request - if I get parentId on php first?
$t = executeQuery('SELECT parentId FROM table WHERE id = :Id;', $id);
if ($t) {
    $id = $t;
}
$t = executeQuery('SELECT * FROM table WHERE id = :id OR parentId = :id ORDER BY id;', $id);
PS: max depends rows < 70
PPS:
id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY product ALL PRIMARY,parentId    NULL    NULL    NULL    73415   Using where
2   DEPENDENT SUBQUERY  product const   PRIMARY,parentId    PRIMARY 4   const   1
                Change the IN for an equal =
SELECT ... 
FROM table 
WHERE id = :id OR parentId = :id OR id = (
    SELECT parentId 
    FROM table 
    WHERE id = :id
    )
or change it to a join:
SELECT ... 
FROM table 
    inner join ( 
        SELECT parentId 
        FROM table 
        WHERE id = :id
    ) s on s.parentID = table.id or s.parentID = table.parentID
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With