Question

I have 3 mysql tables show below. in this case, tbl_a is join table relating tbl_b and tbl_c. I would like to denormalize tbl_a

tbl_a schema

b_id, c_id, id, x,y,z

tbl_b schema

id, a, b, c

tbl_c schema

id, d, e, f

The idea is that for each id in tbl_a, I want to replace b_id and c_id with the full entries from their respective tables.

I have the query

select a,b,c,d,e,f,x,y,z from tbl_a
INNER JOIN tbl_b on tbl_a.b_id = tbl_b.id
INNER JOIN tbl_c on tbl_a.c_id = tbl_c.id;

But this results in 2 rows for each id in tbl_a.

Can someone explain why this doesn't work?

Was it helpful?

Solution

any chance to have duplicate id's in tbl_a?

the query is correct - check http://sqlfiddle.com/#!8/9c666/1

CREATE TABLE `tbl_a` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `b_id` int(11) NOT NULL,
  `c_id` int(11) NOT NULL,
  `xyz` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ;

CREATE TABLE `tbl_b` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `abc` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ;

CREATE TABLE `tbl_c` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `def` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ;


INSERT INTO `tbl_b` (`id`, `abc`) VALUES
(1, 'b1'),
(2, 'b2'),
(3, 'b3'),
(4, 'b4');


INSERT INTO `tbl_c` (`id`, `def`) VALUES
(1, 'c1'),
(2, 'c2'),
(3, 'c3');


INSERT INTO `tbl_a` (`b_id`, `c_id`, `xyz`)
SELECT (ABS(CRC32(UUID())) % 4) + 1, (ABS(CRC32(UUID())) % 3) + 1, SUBSTRING(UUID(), 3, 5);

SELECT * FROM tbl_a;

SELECT * FROM tbl_a
INNER JOIN tbl_b on tbl_a.b_id = tbl_b.id
INNER JOIN tbl_c on tbl_a.c_id = tbl_c.id;

OTHER TIPS

This probably isn't exactly what you want, but then again, you haven't told us exactly what you want...

SELECT a,b,c,d,e,f,x,y,z 
  FROM tbl_a
  LEFT
  JOIN tbl_b 
    ON tbl_a.b_id = tbl_b.id
  LEFT
  JOIN tbl_c 
    ON tbl_a.c_id = tbl_c.id;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top