Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's slow because this will force three full table scans on persons that then get joined together:</p> <pre><code>LEFT JOIN ( ... GROUP BY `_person`.`_oid` -- the group by here ) `_person_cars` ... WHERE ... -- and the where clauses on _person_cars. </code></pre> <p>Considering the where clauses the left join is really an inner join, for one. And you could shove the conditions before the join with persons actually occurs. That join is also needlessly applied twice.</p> <p>This will make it faster, but if you've an order by/limit clause it will still lead to a full table scan on persons (i.e. still not good) because of the group by in the subquery:</p> <pre><code>JOIN ( SELECT `_person_cars`.`_oid`, IFNULL(GROUP_CONCAT(IF(`_person_cars`.`idx`=0, `_person_cars`.`val`, NULL)), NULL) AS `cars[0]`, IFNULL(GROUP_CONCAT(IF(`_person_cars`.`idx`=1, `_person_cars`.`val`, NULL)), NULL) AS `cars[1]` FROM `person_cars` GROUP BY `_person_cars`.`_oid` HAVING IFNULL(GROUP_CONCAT(IF(`_person_cars`.`idx`=0, `_person_cars`.`val`, NULL)), NULL) = 'BMW' OR IFNULL(GROUP_CONCAT(IF(`_person_cars`.`idx`=1, `_person_cars`.`val`, NULL)), NULL) = 'BMW' ) `_person_cars` ... -- smaller number of rows </code></pre> <p>If you apply an order by/limit, you'll get better results with two queries, i.e.:</p> <pre><code>SELECT `_person`.`_oid`, `_person`.`firstname`, `_person`.`lastname` FROM `_person` JOIN `_person_cars` ON `_person_cars`.`_oid` = `_person`.`_oid` AND `_person_cars`.`val` = 'BMW' GROUP BY -- pre-sort the result before grouping, so as to not do the work twice `_person`.`lastname`, `_person`.`firstname`, -- eliminate users with multiple BMWs `_person`.`_oid` ORDER BY `_person`.`lastname`, `_person`.`firstname`, `_person`.`_oid` LIMIT 10 </code></pre> <p>And then select the cars with an IN () clause using the resulting ids.</p> <p>Oh, and your <code>vals</code> column probably should be a varchar.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload