开发者

mysql left join multiple tables with one-to-many relation

开发者 https://www.devze.com 2023-02-24 16:37 出处:网络
I created a simple test case: CREATE TABLE `t1` ( `id` int NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) CREATE TABLE `t2` (

I created a simple test case:

CREATE TABLE `t1` (
  `id` int NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
)

CREATE TABLE `t2` (
  `id2` int NOT NULL AUTO_INCREMENT,
  `id1` int,
  PRIMARY KEY (`id2`)
)

CREATE TABLE `t3` (
  `id3` int NOT NULL AUTO_INCREMENT,
  `id1` int,
  PRIMARY KEY (`id3`)
)

insert into t1 (id) values (1);

insert into t2 (id1) values (1),(1);

insert into t3 (id1) values (1),(1),(1),(1);

I need to select all DISTINCT data from t1 left join t2 and DISTINCT data from t1 left join t3, returning a total of 6 rows ,1 x (2 [from t2] + 4 [from t3]) = 6, but beacause of the nature of this join I get 8 rows, 1 [from t1] x 2 [from t2] x 4 [from t3] = 8.

select * from t1 left join t2 on (t1.id = t2.id1);
2 rows in set (0.00 sec)

select * from t1 left join t3 on开发者_StackOverflow社区 (t1.id = t3.id1);
4 rows in set (0.00 sec)

select * from t1 left join t2 on (t1.id = t2.id1) left join t3 on (t1.id = t3.id1);
8 rows in set (0.00 sec)

select * from t1 left join t2 on (t1.id = t2.id1) union select * from t1 left join t3 on (t1.id = t3.id1);
4 rows in set (0.00 sec)

What query should I use to get just the 6 rows I need, is it posible without subquery's or I need them (It will be more complicatet in the big query where I need this) ?

I need this for a big query where I allready get data from 8 tables, but I need to get data from 2 more to get all the data I need in just one single query, but when joining the 9th table, the returned data get's duplicated (the 9th table in this simple test case would be t3, and the 8th will be t2).

I hope someone could show me the right path to follow.

Thank you.

UPDATE SOLVED: I realy don't know how to do this test case in one select, but in my BIG query I solved it this way: beacause I used group_concat and group by, I did it by spliting a value in multipe group_concat(DISTINCT ... ) and concat all of them like this

// instead of this
... group_concat(DISTINCT concat(val1, val2, val3)) ...
// I did this
concat(group_concat(DISTINCT val1,val2), group_concat(DISTINCT val1,val3)) ... 

so the distinct on small groups of value prevent all of those duplicates.


I'm not sure if you're looking for at this solution

select * from t1 left join t2 on (t1.id = t2.id1);
union all
select * from t1 left join t3 on (t1.id = t3.id1);


I think there is a small mistake in @nick rulez's query. If it is written like this it really returns 6 rows:

(SELECT * FROM t1 LEFT JOIN t2 ON (t1.id = t2.id1))
    UNION ALL
(SELECT * FROM t1 LEFT JOIN t3 ON (t1.id = t3.id1))
0

精彩评论

暂无评论...
验证码 换一张
取 消