2014-12-23 73 views
0

我有三個表格圖像和參數如下。我在構建查詢時遇到問題。準確的結果不會在一個查詢中顯示。我想從主表中獲取信息。內部連接查詢中的SQL IF語句

表中客戶我填寫的數據來自Regular和Master,Regular在Master Table下。 Iwant聯合查詢下面

查詢1

SELECT Customer.CustomerId, 
     Customer.RefId, 
     Regular.LicenseId, 
     Regular.ControlId, 
     Master.MasterId, 
     Master.FullName, 
     Master.profile 
FROM Customer 
     INNER JOIN Regular 
       ON Customer.RefId = Regular.LicenseId 
     INNER JOIN Master 
       ON Regular.ControlId = Master.MasterId 

查詢2

SELECT Customer.CustomerId, 
     Customer.RefId, 
     Master.FullName, 
     Master.profile 
FROM Customer 
     INNER JOIN Master 
       ON Customer.RefId = Master.MasterId 

結果

enter image description here

如何在一個查詢中得到兩個結果。我厭倦了使用不同的陳述。我能得到這個解決方案...

+0

你想要什麼結果?你能多解釋一下嗎?從帖子\ – Backtrack

+0

瞭解我想要從主表中獲得FullName和個人資料是不明確的。客戶表有正常和碩士混合記錄。 Regular.controlId = Master.MasterId –

+0

畜羣來告訴你要找的是什麼。如果您需要兩次加入同一個表,通常可以使用表別名來完成。 –

回答

0

UNION應包括列

SELECT Customer.CustomerId, 
     Customer.RefId, 
     Regular.LicenseId, 
     Regular.ControlId, 
     Master.MasterId, 
     Master.FullName, 
     Master.profile 
FROM Customer 
     INNER JOIN Regular 
       ON Customer.RefId = Regular.LicenseId 
     INNER JOIN Master 
       ON Regular.ControlId = Master.MasterId 
UNION ALL 
SELECT Customer.CustomerId, 
     Customer.RefId, 
     '' LicenseId, 
     '' ControlId, 
     '' MasterId, 
     Master.FullName, 
     Master.profile 
FROM Customer 
     INNER JOIN Master 
       ON Customer.RefId = Master.MasterId 

UPDATE

的同等數量的聲明一個參數來傳遞查詢字符串(R%或M%)

-- DemoProc 'R' 
CREATE PROCEDURE Demoproc @param VARCHAR(50) 
AS 
    BEGIN 
     SET NOCOUNT ON; 

     IF(@param LIKE 'R%') 
     BEGIN 
      SELECT Customer.CustomerId, 
        Customer.RefId, 
        Regular.LicenseId, 
        Regular.ControlId, 
        Master.MasterId, 
        Master.FullName, 
        Master.profile 
      FROM Customer 
        INNER JOIN Regular 
          ON Customer.RefId = Regular.LicenseId 
        INNER JOIN Master 
          ON Regular.ControlId = Master.MasterId 
     END 
     ELSE IF(@param LIKE 'M%') 
     BEGIN 
      SELECT Customer.CustomerId, 
        Customer.RefId, 
        '' LicenseId, 
        '' ControlId, 
        '' MasterId, 
        Master.FullName, 
        Master.profile 
      FROM Customer 
        INNER JOIN Master 
          ON Customer.RefId = Master.MasterId 
     END 
    END 

GO 
+0

我得到了這兩個記錄在表中,但這不是使用充分綁定gridview你可以使用如果語句是這樣的內部連接例如IF RefId像'R%'然後INNER JOIN常規ON Customer.RefId = Regular.LicenseId或如果RefId像'M%'那麼INNER JOIN主站ON Customer.RefId = Master.MasterId –

+0

是的。您可以加入的條件@skgacharya –

+0

我試過,但沒有得到這個說法的結果 –