优化左连接查询或创建等效的mysql查询

时间:2013-08-04 08:54:05

标签: mysql left-join

我创建了两个表。

CREATE TABLE IF NOT EXISTS `table2` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `hash_id` char(24) NOT NULL DEFAULT '0',
  `name` varchar(64) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  KEY `hash_id` (`hash_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `table1` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `table2_id` bigint(20) unsigned DEFAULT NULL,
  `name` varchar(40) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  KEY `table2_id` (`table2_id`),
  CONSTRAINT `table1_ibfk_1` FOREIGN KEY (`table2_id`) REFERENCES `table2` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

根据相应的table1,目标是从table2中选择一些来自table2_id的ID和来自SELECT t1.id, p1.hash_id, p1.name FROM table1 as t1 LEFT JOIN ( SELECT id,name,hash_id FROM table2) as p1 ON t1.table2_id = p1.id WHERE t1.id IN ('1','3') 的信息。使用LEFT JOIN的以下查询给出了我想要的内容。

{{1}}

但似乎效率不高。如何优化?或者你可以建议一些等效的查询?你可以在这里看到解释的结果。 http://sqlfiddle.com/#!2/5502f/13/0

2 个答案:

答案 0 :(得分:1)

为什么你需要在所有这些列上保持联接。只需在相关的列上进行左连接即可。以下是

 SELECT t1.id, t2.hash_id, t2.name , t2.id
 FROM table1 as t1
 LEFT JOIN table2 t2
 ON t1.table2_id = t2.id
 WHERE t1.id IN ('1','3')

答案 1 :(得分:0)

试试这个

     SELECT t1.id, t2.hash_id, t2.name , t2.id as id2
     FROM table1 as t1
     LEFT JOIN table2 t2
     ON t1.table2_id = t2.id
     WHERE t1.id IN ('1','3')

FIDDLE