mysql - How to specify sort order on multiple self joins -
i've attribute table like
create table attributes ( attribute_id int, product_id int, random int, unique key (attribute_id,random,product_id), key (product_id) );
random
random integer number calculated on insert shuffling products (that's o.k. needs). there self-join queries like
select distinct x.product_id attibutes x inner join attributes y on x.product_id=y.product_id inner join attributes z on x.product_id=z.product_id x.attribute_id in (20000085,20000090) , y.attribute_id in (10000007) , z.attribute_id in (30000050,30000040,30000012) limit 0,100;
as can see want select products have @ least 1 attribue in each number range. mysql clever choose table alias first query itself, depending on selectivity of unique key. expected result sorted in order of column random
because of unique key. how can advise mysql revert order? when adding order x.random desc
happen mysql uses filesort ordering because if uses table alias y
base query (because of better selectivity of attribute id 10000007) has use unique key of alias x
. problem is: don't know alias mysql use (it's decided query optimizer). how specify order direction?
(i want note table contains 60 million rows, usage of filesort or not significant in response time)
you might check if version faster:
select a.product_id attibutes a.attribute_id in (20000085, 20000090, 10000007, 30000050, 30000040, 30000012) group a.product_id having sum(a.attribute_id in (20000085, 20000090) ) > 0 , sum(a.attribute_id in (10000007) ) > 0 , sum(a.attribute_id in (30000050, 30000040, 30000012) ) > 0 order a.rand limit 0, 100;
the group by
should same effort select distinct
. still incur overhead sorting random number, formulation works performance-perspective.
edit:
if put random number in products table, following might want:
select p.* products p exists (select 1 attributes p.product_id = a.product_id , a.attribute_id in (20000085, 20000090) ) , exists (select 1 attributes p.product_id = a.product_id , a.attribute_id in (10000007) ) , exists (select 1 attributes p.product_id = a.product_id , a.attribute_id in (30000050, 30000040, 30000012) ) order p.rand limit 5;
hmmm, if store random number in products table, join
query , use in order by
. might work.
Comments
Post a Comment