mysql - Optimal Query for a problem -
i have news
table following:
create table `news` ( `title` varchar(255) not null, `hash` char(40) not null, primary key (`hash`) ) engine=innodb default charset=utf8;
and, votes
table following:
create table `votes` ( `hash` char(40) not null, `user_id` varchar(255) not null, `vote_type` enum('up','down') default null, primary key (`hash`) ) engine=innodb default charset=utf8;
now want when user logged in-
this_is_a_title hash_12312312 null
this_is_a_title hash_12312313 up
this_is_a_title hash_12312314 null
this_is_a_title hash_12312315 down
can suggest optimal single query this?
i think question not clear. sorry that. null field meant new doesn't has vote casted user or anybody.
my version -
select news.*, votes.vote_type news left outer join votes on votes.`hash` = news.`hash` , votes.`user_id` = #
select * news join votes on news.hash = votes.hash votes.user_id = #;
this select
votes on news articles specific user id #
. tables joined hash
primary key. it's optimal given current configuration. add index user_id
additional optimization.
note: since looking optimal, encourage not use left join
. assuming news
articles grow on time, using straight join
limit result set votes user has cast. which, on average, should smaller. however, need compensate in logic - i.e. absence of news record means no vote versus null
result.
Comments
Post a Comment