2014-08-29 47 views
0

假設我有兩個表「tbl_people」和「tbl_spouses」。SQL - 如果ID> 0,則加入

tbl_people structure: 
- PeopleID 
- Name 
- Prename 
- SpouseID_FK 

tbl_spouses structure: 
- SpouseID 
- Name 
- Prename 

等等(也許不是最好的例子,因爲配偶也是人,但不管)。

現在我想擁有人民配偶的名字。如果SpouseID_FK = 0,記錄也應顯示,但配偶的姓氏應爲「」。

SELECT tbl_people.PeopleID, 
     tbl_people.Name, 
     tbl_people.Prename, 
     tbl_spouses.Prename AS PrenameOfSpouse 
FROM tbl_people 
INNER JOIN tbl_spouses ON tbl_people.SpouseID_FK = tbl_spouses.SpouseID 

這個SQL的問題是,它只是顯示的記錄,它不具備SpouseID_FK值0。

任何人都可以幫助我嗎?

+2

不清楚的問題,但我認爲它可以使用來解決'左外Join',而不是'內join' – 2014-08-29 07:33:25

回答

1

這也會顯示tbl_people誰也沒有配偶的記錄。

SELECT tbl_people.PeopleID, tbl_people.Name, tbl_people.Prename, 
     tbl_spouses.Prename AS PrenameOfSpouse 
FROM tbl_people 
LEFT JOIN tbl_spouses ON tbl_people.SpouseID_FK = tbl_spouses.SpouseID 
+1

謝謝你,它的工作! :) – user2871190 2014-08-29 08:01:52