我的问题类似于这个问题:https://stackoverflow.com/a/7517904
我有四张桌子,我把它们和钥匙A和B连接起来:
A
A B C
1 a c B
A B D
1 a d
1 a e C
A B E
1 a h
1 a i D
A B F
1 a k
1 a l 我想把这两张桌子连在一起,结果应该是:
A B C D E F
1 a c d h k
1 a c e i l 我的实际结果如下:
A B C D E F
1 a c d h k
1 a c e h k
1 a c d h l
1 a c e h l
1 a c e i l
1 a c d i l
1 a c d i k
1 a c e i k问题是,我得到了所有的组合。我希望有尽可能少的行。我尝试了另一个线程的解决方案,使用行号:
SELECT*
FROM (SELECT @rowsnum := @rowsnum + 1 AS ae1num,
Concat(ae1.a, ae1.b) AS id,
ae1.*
FROM A as ae1,
(SELECT @rowsnum := 0) r
ORDER BY ae1.a,
ae1.b) ae1
LEFT JOIN (SELECT aenum,
Concat(ae111.a, ae111.b) AS id,
aecm.*
FROM (SELECT @rownum := @rownum + 1 AS aenum,
Concat(ae11.a, ae11.b) AS id,
ae11.*
FROM A as ae11,
(SELECT @rownum := 0) a
ORDER BY ae11.a,
ae11.b) ae111
LEFT JOIN B as aecm
ON ae111.a = aecm.a
AND ae111.b = aecm.b
ORDER BY ae111.a,
ae111.b) aec
ON ae1.a = aec.a
AND ae1.b = aec.b
AND aec.aenum = ae1.ae1num 我希望我把我的问题描述得够清楚了。
发布于 2017-12-12 17:12:25
你的意思是,我想你想把A连接到B的第一行,C的第一行和D的第一行,A连接到B的第二行,C的第二行和D的第二行。
关系数据库在行中没有任何隐含的序列;如果要拥有序列,则必须是列值。这是有充分理由的,但太长,无法在此解释。结果是,您需要一个序列列,如下所示:
create table a (a integer, b varchar(1), c varchar(1));
insert into a (a, b, c) values (1, 'a', 'c');
create table b (a integer, b varchar(1), sequence integer, d varchar(1));
insert into b (a, b, sequence, d) values (1, 'a', 1, 'd');
insert into b (a, b, sequence, d) values (1, 'a', 2, 'e');
create table c (a integer, b varchar(1), sequence integer, e varchar(1));
insert into c (a, b, sequence, e) values (1, 'a', 1, 'h');
insert into c (a, b, sequence, e) values (1, 'a', 2, 'i');
create table d (a integer, b varchar(1), sequence integer, f varchar(1));
insert into d (a, b, sequence, f) values (1, 'a', 1, 'k');
insert into d (a, b, sequence, f) values (1, 'a', 2, 'l');然后查询如下:
select distinct
a.a,
a.b,
a.c,
b.d,
c.e,
d.f
from
a
join
b on a.a = b.a and a.b = b.b
join
c on a.a = c.a and a.b = c.b and c.sequence = b.sequence
join
d on a.a = d.a and a.b = d.b and d.sequence = b.sequence;结果是:
+---+---+---+---+---+---+
| a | b | c | d | e | f |
+---+---+---+---+---+---+
| 1 | a | c | d | h | k |
| 1 | a | c | e | i | l |
+---+---+---+---+---+---+
2 rows in set (0.00 sec)https://stackoverflow.com/questions/47775056
复制相似问题