需要帮助优化MySQL查询

时间:2010-09-23 17:56:26

标签: sql mysql query-optimization

我有一个复杂的SQL查询,我想优化嵌套的“子查询”

    SELECT
'likes' `type`,
entry_date item_date,
CASE `type`
    WHEN 'entry_id' THEN entry_id
    WHEN 'member_id' THEN f.member_id
    WHEN 'topic_id' THEN entry_id
END    
AS item_id,
CASE `type`
    WHEN 'entry_id' THEN (SELECT title FROM exp_weblog_titles WHERE entry_id=item_id)
    WHEN 'member_id' THEN (SELECT screen_name FROM exp_members WHERE member_id=item_id)
    WHEN 'topic_id' THEN (SELECT title FROM exp_forum_topics WHERE topic_id=item_id)
END    
AS item_title,
CASE `type`
    WHEN 'member_id' THEN (SELECT username FROM exp_members WHERE member_id=item_id)
    ELSE ''
END    
AS  item_url_title,
f.type parent_type,
CASE `type`
    WHEN 'entry_id' THEN (SELECT weblog_id FROM exp_weblog_titles WHERE entry_id=item_id)
    WHEN 'member_id' THEN ''
    WHEN 'topic_id' THEN (SELECT forum_id FROM exp_forum_topics WHERE topic_id=item_id)
END    
AS parent_id,
CASE `type`
    WHEN 'entry_id' THEN ''
    WHEN 'member_id' THEN ''
    WHEN 'topic_id' THEN (SELECT forum_name FROM exp_forums WHERE forum_id=parent_id)
END    
AS parent_title,         
m.member_id actor_member_id,
screen_name actor_screen_name,
username actor_username,
photo_filename actor_photo,
avatar_filename actor_avatar
FROM exp_favorites f, exp_members m
WHERE f.member_id=m.member_id

您可以注意到,在子查询中,对于同一行但不同的字段,会多次查询某些表。
就像,我有

SELECT screen_name FROM exp_members WHERE member_id=item_id  

SELECT username FROM exp_members WHERE member_id=item_id  

我活着看到组合来模仿reuest和服务器负载的数量。

有办法做到这一点吗?有什么建议吗?

UPD。表结构如下:
    CREATE TABLE exp_favorites
  favorites_id int(10)unsigned NOT NULL auto_increment,
  type varchar(16)NOT NULL默认'entry_id',
  author_id int(10)unsigned NOT NULL默认值'0',
  entry_id int(10)unsigned NOT NULL,
  member_id int(10)unsigned NOT NULL,
  site_id smallint(3)unsigned NOT NULL默认值'1',
  entry_date int(10)unsigned NOT NULL,
  notes文本NOT NULL,
  public char(1)NOT NULL默认'y',
  PRIMARY KEY(favorites_id),
  KEY author_idauthor_id),
  KEY entry_identry_id),
  KEY member_idmember_id),
  KEY site_idsite_id),
  KEY publicpublic),
  KEY typetype

1 个答案:

答案 0 :(得分:1)

您可以这样做:

SELECT
'likes' `type`,
entry_date item_date,
CASE `type`
    WHEN 'entry_id' THEN entry_id
    WHEN 'member_id' THEN f.member_id
    WHEN 'topic_id' THEN entry_id
END    
AS item_id,
CASE `type`
    WHEN 'entry_id' THEN wt.title
    WHEN 'member_id' THEN m2.screen_name
    WHEN 'topic_id' THEN ft.title
END    
AS item_title,
...
FROM exp_favorites f
inner join exp_members m ON f.member_id=m.member_id
left outer join exp_weblog_titles wt on wt.entry_id=f.item_id
left outer join exp_members m2 on m2.entry_id=f.item_id
left outer join exp_forum_topics ft on ft.entry_id=f.item_id