我是这个sql世界的新手。在我是一名SQL和SQL知识有限的开发人员之后简单的连接。我在为一对多关系编写sql join时遇到了问题。这是我的问题 -
例如如果我有一个VendorsList表:
id Name address
1 sales Japan
2 marketing US
以及:
的VendorContacts表id vendorid vendorempname
1 1 Tom
2 1 Bill
3 2 Jessy
4 1 Rachel
5 2 Rob
现在加入后我想要的是:
vendor_id Name address vendorempname
1 Sales Japan Tom
1 Sales Japan Bill
1 Sales Japan Rachel
2 Marketing US Jessy
2 Marketing US Rob
任何人都可以帮忙写这个吗?
答案 0 :(得分:2)
这应该做的工作
Select v.vendor_id, v.name, v.address, vc.vendorempname
from VendorContacts vc
join VendorList v
on v.id = vc.vendor_id
order by vc.vendor_id
答案 1 :(得分:0)
SELECT b.vendor_id, a.Name, a.address, b.vendorempname
FROM VendorList a, VendorContact b
WHERE a.id = b.vendor_id
ORDER BY b.vendor_id;
答案 2 :(得分:0)
请看一下:
Select vl.vendorId,vl.name,vl.address,vc.vendorempname
from vendorlist as vl
right join VendorContacts as vc
on vl.vendorId = vc.vendorId
order by vc.vendorId asc
请尝试此操作并获取您想要的数据。
答案 3 :(得分:0)
尝试以下查询。它提供了您正在寻找的确切结果,除了代表名称的顺序..
WITH VENDORLIST AS
(SELECT '1' ID, 'sales' Name, 'Japan' address FROM DUAL
UNION
SELECT '2' ID, 'marketing' Name, 'US' address FROM DUAL),
VENDORCONTACTS AS
(
SELECT '1' ID, '1' vendorid, 'Tom' vendorempname FROM DUAL
UNION
SELECT '2' ID, '1' vendorid, 'Bill' vendorempname FROM DUAL
UNION
SELECT '3' ID, '2' vendorid, 'Jessy' vendorempname FROM DUAL
UNION
SELECT '4' ID, '1' vendorid, 'Rachel' vendorempname FROM DUAL
UNION
SELECT '5' ID, '2' vendorid, 'Rob' vendorempname FROM DUAL
)
SELECT VENDORID, NAME, ADDRESS, vendorempname FROM VENDORLIST, VENDORCONTACTS
WHERE VENDORCONTACTS.vendorid = VENDORLIST.ID
ORDER BY VENDORID, NAME, ADDRESS, vendorempname
;