2013-08-04 85 views
-1

我创建了两个表。优化左连接查询或创建等效的mysql查询

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; 

目标有两个由自己的ID和信息table2根据相应table2_id选择table1某些行。以下带有LEFT JOIN的查询给了我正是我想要的。

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

+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') 
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

+0

@AntonGuba如果你看他发布他的答案的时间,我先发布答案,我认为他复制粘贴我的答案。 –