Вопрос

this is driving me crazy, im trying really hard to make a join with 3 tables on mysql, what i want is, to select all suscriptors a user is suscribed to, and for it, i got this tables

user(id, nombre)
suscriptor(id, nombre)
suscripcion(id, userid, suscriptorid)

the query i use is this one:

select u.nombre, sr.nombre, s.suscriptorid from user u
       inner join suscripcion s on s.userid = u.id
       inner join suscriptor sr on sr.id = s.suscriptorid
where u.id = 1;

and it works fine, but when I use explain to check the query, when there's only one result, i mean, when the user with id = 1 only is suscribed to one suscriptor everything is fine for me cause total rows scanned is 1 * 1 * 1. the problem is when the user is suscribed to more than one suscriptors, cause it displays:

row is 1 and type is const in table u(user)
row is 1 and type is ref in table s(suscripcion)
row is 5(which is the total rows) and type is all in table sr(suscriptor)

I've tried these types of index combination:

  • in table suscripcion: index UI(userid) and index SI(suscriptorid)

and seems to only use one of the index, and keeps scanning all results in table suscriptor

  • I've even tried with compound index : index USI(userid, suscriptorid) but ignore the second index again and scan all rows in table suscriptor.

thanks in avanced.

Это было полезно?

Решение

If you have only 5 rows the query planner won't use the index because it's faster to read all 5 rows then to use the index. Try testing with a few hundred rows. You could also suggest index to see if it's eligible at all

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top