Mysql与同一列中的多个索引连接

时间:2013-11-11 09:32:01

标签: mysql join where database-indexes

我的MySQL查询有问题,可能还有加入。

我的数据库结构如下:

Table A
    id, nameA, nameB
Table B
    some_stuff, ids
第二个表中的

ids是一个字符串,其中包含第一个表中的一个或多个id

我想从两行获取数据,例如:

Result
    some_stuff, ids, firstId, firstNameA, firstNameB
    some_stuff, ids, secondId, secondNameA, secondNameB

是否可以使用单个查询获取它,可能不使用子查询?

1 个答案:

答案 0 :(得分:0)

选中此sqlfiddle

<强>查询:

SELECT some_stuff, ids, id, nameA, nameB FROM TabA JOIN TabB ON INSTR(ids, id)

表格结构:

CREATE TABLE IF NOT EXISTS `TabA` (
  `id` int(8) unsigned NOT NULL AUTO_INCREMENT,
  `nameA` varchar(128) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `nameB` varchar(16) CHARACTER SET utf8 NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


CREATE TABLE IF NOT EXISTS `TabB` (
  `bid` int(8) unsigned NOT NULL AUTO_INCREMENT,
  `ids` varchar(128) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `some_stuff` varchar(16) CHARACTER SET utf8 NOT NULL DEFAULT '',
  PRIMARY KEY (`bid`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

INSERT INTO TabA(id,nameA,nameB) VALUES(1,"nm1","nmm1"),
(2,"nm2","nmm2"),
(3,"nm3","nmm3"),
(4,"nm4","nmm4"),
(5,"nm5","nmm5");

INSERT INTO TabB(bid,ids,some_stuff) VALUES(1,"1,2","some_stuff1"),
(2,"1,3","some_stuff2"),
(3,"2","some_stuff3"),
(4,"2,4","some_stuff4"),
(5,"1,2,3","some_stuff5");

输出

SOME_STUFF  IDS ID  NAMEA   NAMEB

some_stuff1 1,2 1   nm1 nmm1
some_stuff1 1,2 2   nm2 nmm2
some_stuff2 1,3 1   nm1 nmm1
some_stuff2 1,3 3   nm3 nmm3
some_stuff3 2   2   nm2 nmm2
some_stuff4 2,4 2   nm2 nmm2
some_stuff4 2,4 4   nm4 nmm4
some_stuff5 1,2,3   1   nm1 nmm1
some_stuff5 1,2,3   2   nm2 nmm2
some_stuff5 1,2,3   3   nm3 nmm3

如果有任何错误让我知道。