2

我有一个查询问题,例如这个我可以检索记录:

SELECT 
l.*, 
ll.f_cocacola as cocacola, 
 le.name AS deposit, 
 lp.price
FROM 
 KPC AS l, 
 KPC_cocacola AS ll, 
 KPC_deposit AS le, 
 KPC_price AS lp 
WHERE 
l.cod_deposit = le.id_deposit 
AND l.code = ll.code
AND lp.code = l.code
AND l.code_deposit = '002365' 

但现在我需要包含另一个表中的另一个日期 -intranet- 具有字段codeurl然后需要从这个表中显示url字段.. 请记住,关系在code字段上。

所以我以这种方式更改查询:

SELECT l.*,ll.f_cocacola as cocacola, le.name AS deposit, 
lp.price, lintranet.url 
FROM tableX AS l, intranet_cocacola AS ll, tableX_deposit AS le, 
tableX_price AS lp, 
tableX_intranet as lintranet 
WHERE l.code_deposit = le.id_deposit
AND l.code = ll.code
AND lp.code = l.code 
AND l.code = lintranet.code
AND l.code_deposit = '456852147'

但问题是某些记录没有url,如果不存在url,那么这个查询不会向我显示记录.. 即使没有与我想要的记录关联的url ,我也需要它看到那个记录,谢谢

4

3 回答 3

3

使用 ANSI 连接语法重写您的查询并使用LEFT JOIN

SELECT  l.*, ll.f_cocacola as cocacola, le.name AS deposit, 
        lp.price, lintranet.url 
FROM    tableX AS l,
JOIN    intranet_cocacola AS ll
ON      ll.code = l.code
JOIN    tableX_deposit AS le
ON      le.id_deposit = l.code_deposit
JOIN    tableX_price AS lp
ON      lp.code = l.code
LEFT JOIN
        tableX_intranet as lintranet
ON      lintranet.code = l.code
WHERE   l.code_deposit = '456852147'
于 2012-04-17T22:53:22.113 回答
2

改用LEFT JOIN

SELECT l.*,ll.f_cocacola as cocacola, le.name AS deposit, 
lp.price, lintranet.url 
FROM tableX AS l, intranet_cocacola AS ll, tableX_deposit AS le, 
tableX_price AS lp
LEFT JOIN tableX_intranet as lintranet ON l.code = lintranet.code -- <<<<<
WHERE l.code_deposit = le.id_deposit
AND l.code = ll.code
AND lp.code = l.code 
AND l.code_deposit = '456852147'

PS:我个人更喜欢显式INNER JOIN,而不是使用逗号分隔的表枚举加入。因为它可以更好地了解查询的作用

于 2012-04-17T22:52:11.640 回答
1

我知道您已经有了答案,但是我看到您的问题是针对 Oracle 数据库提出的...虽然我认为 LEFT JOIN 有效,因为它是标准 SQL,Oracle 有自己的版本,因此您可以看到相同的查询编写如下:

SELECT l.*,ll.f_cocacola as cocacola, le.name AS deposit, lp.price, lintranet.url 
  FROM tableX AS l, intranet_cocacola AS ll, tableX_deposit AS le, tableX_price AS lp, tableX_intranet as lintranet
 WHERE l.code_deposit = le.id_deposit
   AND l.code = ll.code
   AND lp.code = l.code 
   AND l.code_deposit = '456852147'
   AND l.code = lintranet.code(+)  //<-- this is how a left/right join is written
                                   //on Oracle's SQL, you add "(+)" next to the 
                                   //field of the table that may not have 
                                   //matching records.
于 2012-04-17T23:22:20.547 回答