2011-12-13 71 views
0

我需要一個SQL stament會給我這樣的事情,其中​​一個字段是否爲空,它不這樣做的加入我需要做一個SQL如果然後其他連接表,如果該字段不爲空?

SELECT AdminID,tblapartments.NameNo, tblgarages.GarageID, tblclients.Name FROM tbladmin,tblclients,tblgarages,tblapartments WHERE tblclients.ClientID =tbladmin.ClientID AND 
IF (tbladmin.ApartmentID != null) 
{ 
tblapartments.ApartmentID = tbladmin.ApartmentID 
} 
AND If(tbladmin.GarageID != Null) 
{ 
tblgarges.GarageID = tbladmin.GarageID 
} 
+0

你爲什麼不試試內連接加入 – 2011-12-13 18:56:33

+0

我該怎麼做? – owen 2011-12-13 18:58:02

+0

我是新來的sql:S – owen 2011-12-13 18:58:09

回答

2

除非我失去了一些東西,這應該只是一個外部聯接。

SELECT 
    AdminID, 
    tblapartments.NameNo, 
    tblgarages.GarageID, 
    tblclients.Name 
FROM 
    tbladmin INNER JOIN tblclients ON tbladmin.ClientID = tblclients.ClientID 
    LEFT OUTER JOIN tblgarages ON tbladmin.GarageID = tblgarages.GarageID 
    LEFT OUTER JOIN tblapartments ON tbladmin.ApartmentId = tblapartments.ApartmentID 
2

您可以使用LEFT JOIN S,當加入列不存在於另一表中的結果是很多NULL領域:

SELECT AdminID,tblapartments.NameNo, tblgarages.GarageID, tblclients.Name 
FROM tbladmin 
INNER JOIN tblclients 
    ON tbladmin.ClientID = tblclients.CliendID 
LEFT JOIN tblgarages 
    ON tbladmin.GarageID = tblgarages.GarageID 
LEFT JOIN tblapartments 
    ON tbladmin.ApartmentID = tblapartments.ApartmentID 
1

我不認爲這種類型的if邏輯是SQL標準。你可以用PL/SQL,plpgsql等程序化的SQL語言來實現它......但是爲了完成你以後的工作,我認爲左邊應該加入你應該看到的東西。

SELECT AdminID,tblapartments.NameNo, tblgarages.GarageID, tblclients.Name 
FROM tbladmin a 
join tblclients b on b.ClientID = a.ClientID 
left join tblapartments c on c.ApartmentID = a.ApartmentID 
left join tblgarges d on d.GarageID = a.GarageID 
相關問題