2013-02-20 41 views
0

如何選擇與條件2表並顯示所有數據如何選擇2表狀況並顯示所有數據

store_profile 
id + store_name 
1 | Accessorize.me 
2 | Active IT 
3 | Edushop 
4 | Gift2Kids 
5 | Heavyarm 
6 | Bamboo 

store_fee 
id + store_id + date_end 
1 | 1  | 27-6-2013 
2 | 2  | 29-8-2013 
3 | 3  | 02-6-2013 
4 | 4  | 20-4-2013 

下面是我以前的查詢

$query = "select sp.id, sp.store_name, sf.id, sf.store_id, sf.date_end from store_profile sp, store_fee sf where sf.store_id=sp.id" 

,結果是一樣的東西這樣的:

1 | Accessorize.me 27-6-2013 
2 | Active IT  29-8-2013 
3 | Edushop   02-6-2013 
4 | Gift2Kids  20-4-2013 

,但我想是顯示所有的商店名稱包括date_end但如果n Ødate_end仍然可以顯示商店名稱與空date_end

回答

1

您想要使用外部聯接。與外連接,在連接表中的列不需要匹配連接表的條件列,得到的結果:

SELECT * FROM store_profile sp LEFT JOIN store_fee sf ON (sf.store_id = sp.id) 
+0

感謝@Explosion丸簡單,工作對我來說.. – rusly 2013-02-20 02:19:31

1

使用左連接:

select sp.id, sp.store_name, sf.id, sf.store_id, sf.date_end 
from store_profile sp left join store_fee sf on sf.store_id=sp.id 
1

您正在使用被解釋爲INNER JOIN,這意味着沒有store_profile的相應條目門店將不會顯示的語法向上。你想用LEFT JOIN

SELECT sp.id, sp.store_name, sf.id, sf.store_id, sf.date_end 
FROM store_profile sp 
LEFT JOIN store_fee sf 
ON sf.store_id=sp.id 

LEFT JOIN意味着,在第一個表中的所有記錄將被退回,即使有沒有第二個表匹配。

相關問題