-1

我创建了两个表。

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的 id 和信息从中选择一些行。以下带有 LEFT JOIN 的查询给了我我想要的东西。table2table2_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')

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

4

2 回答 2

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')
于 2013-08-04T09:01:22.457 回答
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')

小提琴

于 2013-08-04T08:58:29.460 回答