SELECT count(*) AS co FROM todo WHERE EXISTS ( SELECT * FROM user_todo_send uts WHERE uts.id_todo = todo.id AND uts.id_user = $id_user ) OR EXISTS ( SELECT * FROM todo_task_send ts WHERE ts.id_todo = todo.id AND ts.id_user_to = $id_user ) AND todo.confirm = 1 

It is necessary to obtain data from one table ( todo ), but so that the ID is the other two tables.

The request works, but EXPLAIN issues:

enter image description here

    1 answer 1

    You have a lot of subqueries. It is better to use join-s Something like this:

     SELECT count(*) as co FROM todo t left join user_todo_send uts on(t.id = uts.id_todo) left join todo_task_send tts on(t.id = tts.id_todo) where todo.confirm = 1 and ( uts.id_todo is not null or tts.id_todo is not null ) 
    • +1 but how to make a condition that will count the quantity both there and there and sum it up, since you need to get their sum and not the sum of unique ones - modelfak
    • Alternatively, try changing the condition like this: (uts.id_todo is not null or tts.id_todo is not null) - zig1375