Question

I have a problem with a MySQL query, possibly with a join.

My database structure is like this:

Table A
    id, nameA, nameB
Table B
    some_stuff, ids

ids in the second table is a string containing one or more id from the first table

I want to get the datas from both lines, something like:

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

Is it possible to get it with a single query, possibly without using subqueries?

No correct solution

OTHER TIPS

Check this sqlfiddle

Query:

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

Table structure:

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");

Output:

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

If any mistake let me know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top