2012-04-17 202 views
2

我有一個查詢的問題,比如這一個我可以檢索記錄:SQL查詢,不顯示所有記錄

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-具有領域代碼網址則需要從該表中網址秀場..記住,我們的關係就代碼場。

,所以我更改查詢,以這樣的方式

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關聯到我希望看到recorda的記錄,由於

回答

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

你的答案是相當更加清晰,我選擇了這一個,我也給予好評的@zerkms回答 – hibigo 2012-04-17 23:15:28

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,而不是使用逗號分隔的表枚舉連接。因爲它給出了查詢確實

+0

兩個答案都非常好,現在我不知道我可以選擇你的名譽和Quassnoi :( – hibigo 2012-04-17 23:13:28

1

我知道你已經有一個答案,但我看到你的問題用Oracle數據庫製作......而我認爲LEFT JOIN的作品,因爲它是STANDAR 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. 
+0

謝謝你,我也投了你的答案,是很好的一個..晚安 – hibigo 2012-04-17 23:23:56

+1

此語法'9i'及以上 – Quassnoi 2012-04-18 08:57:38

+0

棄用@Quassnoi真的嗎?不知道......強硬,我更喜歡它! – 2012-04-18 10:21:23