【发布时间】:2011-04-13 11:47:00
【问题描述】:
我创建了一个简单的测试用例:
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);
我需要从 t1 left join t2 中选择所有 DISTINCT 数据和从 t1 left join t3 中选择 DISTINCT 数据,总共返回 6 行,1 x (2 [from t2] + 4 [from t3]) = 6,但是由于这个连接的性质,我得到 8 行,1 [来自 t1] x 2 [来自 t2] x 4 [来自 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 (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)
我应该使用什么查询来获取我需要的 6 行,是否可以不使用子查询或者我需要它们(在我需要这个的大查询中会更复杂)?
我需要这个来进行一个大查询,我已经从 8 个表中获取数据,但是我需要从另外 2 个表中获取数据才能在一个查询中获取我需要的所有数据,但是当加入第 9 个表时,返回的数据会重复(在这个简单的测试用例中,第 9 个表是 t3,第 8 个是 t2)。
我希望有人能告诉我正确的道路。
谢谢。
更新已解决: 我真的不知道如何在一次选择中执行此测试用例,但在我的 BIG 查询中我以这种方式解决了它:因为我使用了 group_concat 和 group by,我通过在 multipe group_concat(DISTINCT ... ) 并像这样连接所有这些
// instead of this
... group_concat(DISTINCT concat(val1, val2, val3)) ...
// I did this
concat(group_concat(DISTINCT val1,val2), group_concat(DISTINCT val1,val3)) ...
因此,小组价值的独特性可以防止所有这些重复。
【问题讨论】:
-
你怎么能有一个默认值的主键?
-
@nick rulez :我没有注意到,我将 t2,t3 中的列从 id 更改为 id2,id3 和 mysql 放置了默认值,更新了问题。 ...:P
标签: mysql