问个问题,(MySQL)A表的字端有code_name,code_id,code_field,另一表B表有很多属性,例如国籍,籍贯等等,国籍子查询查法为select code_name form A表 where code_id=B表.gj_id and code_field = 'gj'。
现在遇到的困难时子查询太慢了,而且除了国籍外还有籍贯等属性,如果都去用子查询的话,一次估计几分钟。这种情况下能不能用联表……
请问有没有什么好的解决方案!
select
(select code_name from A where code_id = B.GJ and field_name = 'GJ') as GJ, -- 国籍
(select code_name from A where code_id = B.JG and field_name = 'JG') as JG, -- 籍贯
(select code_name from A where code_id = B.SYD and field_name = 'SYD') as SYD-- 生源地
FROM B;
以下为大致的表结构(不好发正式的表结构)
A表
CREATE TABLE `NewTable` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键' ,
`GJ` int(11) NOT NULL ,
`JG` int(11) NOT NULL ,
`MZ` int(11) NOT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=MyISAM
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
AUTO_INCREMENT=3
CHECKSUM=0
ROW_FORMAT=FIXED
DELAY_KEY_WRITE=0
;
B表
CREATE TABLE `NewTable` (
`id` int(11) NOT NULL ,
`code_id` int(11) NOT NULL ,
`code_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`field_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=MyISAM
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
CHECKSUM=0
ROW_FORMAT=DYNAMIC
DELAY_KEY_WRITE=0
;
A表图
B表图
如果用子查询
select
(select code_name from B where code_id = A.GJ and field_name = 'GJ') as GJ
(select code_name from B where code_id = A.MZ and field_name = 'MZ') as MZ
(select code_name from B where code_id = A.JG and field_name = 'JG') as JG
FROM
A;
我的尝试
select
B.code_name,C.code_name
FROM
A
JOIN B
ON
B.code_id = A.GJ AND B.field_name = 'GJ'
JOIN B as C
ON
C.code_id = A.MZ AND C.field_name = 'MZ'
这种嵌套join的写法,竟然比子查询还要漫长……这是什么原因呢,知道的也可以说一下哈
aluckdog
海绵宝宝撒
翻阅古今