我有带有字段的表:
line_id, point_address:
1 | Address1
1 | Address2
2 | Address1
2 | Address3
3 | Address2
3 | Address3
为得到结果,我需要每个line_id都具有一行的表,并且line_id的两个point_address值都在单独的行中:
line_id,point_address_1,point_address_2:
1 | Address1 | Address2
2 | Address1 | Address3
3 | Address2 | Address3
我试图创建自我联接,但是我得到的是每个line_id具有point_address字段的所有组合的4个结果。 取得单一结果的最佳方法是什么
答案 0 :(得分:1)
假设每个line_id
上只有两个地址,则可以通过在结果表中强制point_address
上的顺序来解决此问题:
SELECT
l1.line_id, l1.point_address AS point_address1,
l2.point_address AS point_address2
FROM line_address l1 JOIN line_Address l2 ON l1.line_id = l2.line_id
WHERE l1.point_address < l2.point_address;
line_id point_address1 point_address2
---------- -------------- --------------
1 Address1 Address2
2 Address1 Address3
3 Address2 Address3
请注意,这仅在上述假设下有效,因此,如果我们添加
INSERT INTO line_address (line_id, point_address) VALUES (3, 'Address4');
精选产量
line_id point_address1 point_address2
---------- -------------- --------------
1 Address1 Address2
2 Address1 Address3
3 Address2 Address3
3 Address2 Address4
3 Address3 Address4
当您尝试将行划分为列时,关系代数并不那么友好。