1

我是这个 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

任何人都可以帮助书面加入吗?

4

4 回答 4

3

这应该做的工作

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
于 2013-07-05T05:43:04.813 回答
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;
于 2013-07-05T05:43:20.307 回答
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
            ;
于 2014-04-16T05:32:26.167 回答
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

请试试这个,会得到你想要的数据。

于 2013-07-05T07:30:22.750 回答