我的查询有问题,例如我可以检索这些记录:
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中包含另一个日期 - 其中包含 code 和 url 字段,然后需要从此表中显示 url 字段..请记住,该关系位于代码字段。
所以我以这种方式更改查询:
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 我也希望看到该记录,谢谢
答案 0 :(得分: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'
答案 1 :(得分: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
,而不是使用逗号分隔的表枚举加入。因为它可以更好地了解查询的作用
答案 2 :(得分: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.