2016-02-16 48 views
1

的情況我有三個表2008數據庫按照我的SQL Server:加入一個表(或沒有)的基礎上在SQL

  • 汽車
  • 驅動程序
  • UnavailableDrivers

我想要的是在最終用戶設置@isAvailable = 0時顯示不可用的驅動程序。另一方面,如果isAvailable = 1,那麼最終用戶應該只能看到可用的驅動程序。最後,如果isAvailable爲NULL,那麼用戶應該看到所有的驅動程序。

declare @isAvailable bit; 

我需要寫一個這樣的查詢:

Select * 
From Cars c 
Inner join Drivers d on (c.driverId = d.Id) 
CASE 
    WHEN @isAvailable = 0 THEN inner join UnavailableDrivers uc on (c.driverId= uc.Id) 
    WHEN @isAvailable = 1 THEN inner join UnavailableDrivers uc on (c.driverId != uc.Id) 
    ELSE @IsAvailable END 
-- ELSE -> basically DO NOT JOIN UnavailableDrivers 

這是給不正確的語法錯誤,我無法找到不幸數小時正確的語法。其實我也不覺得這個問題是正確的。所以任何幫助解決我的查詢在這個邏輯將不勝感激!

+1

選擇 從轎車Ç LEFT JOIN驅動器D1 ON c.DriverId = d.DriverId LEFT JOIN不可用驅動程序u ON u.DriverId = c.DriverId – chdev77

+0

you will我需要通過動態SQL應用邏輯 –

回答

1

下面的查詢你想:

SELECT * 
FROM Cars c 
INNER JOIN Drivers d ON (c.driverId = d.Id) 
WHERE (@isAvailable IS NULL) -- will not join to UnavailableDrivers is isAvailable is null 
OR (@isAvailable = 0 AND c.driverId IN (SELECT uc.id FROM UnavailableDrivers uc)) -- will join to UnavailableDrivers only if isAvailable equals to 0 
OR (@isAvailable = 1 AND c.driverId NOT IN (SELECT uc.id FROM UnavailableDrivers uc)) -- will join to UnavailableDrivers because isAvailable equals to 1 
+0

我的朋友我想問你一些事情。當NOT IN部分工作時(@ isAvailable = 1),運行時間比其他時間(其他時間爲14-16秒時爲42秒)高。你能否建議一種解決這個問題的方法,也許? @CodeNotFound –

+0

用'(@isAvailable = 1和NOT EXISTS(從不可用的驅動程序uc WHERE uc.id = c.driverId中選擇uc.id) – CodeNotFound

0

可怕的做法,但你問它

USE [DB] 
    GO 

    CREATE PROCEDURE [GetDrivers] 
     @isAvailable bit 
    AS 
    BEGIN 


      IF (@isAvailable = 0) 
      BEGIN 
       Select * From Cars c 
        Inner join Drivers d on (c.driverId = d.Id) 
        inner join UnavailableDrivers uc on (c.driverId= uc.Id) 

      END 
      ELSE 
      begin 
       Select * From Cars c 
        Inner join Drivers d on (c.driverId = d.Id) 
        inner join UnavailableDrivers uc on (c.driverId!= uc.Id) 

      end 



    END 
0
SELECT 
    * 
    , CASE 
    WHEN d.DriverId IS NOT NULL THEN 'Availible' 
    WHEN u.DriverId IS NOT NULL THEN 'Unavailible' 
    ELSE 'Driver is in both' 
    AS 'Driver Status' 
FROM Cars c 
LEFT JOIN Drivers d 
    ON c.DriverId = d.DriverId 
LEFT JOIN UnavailableDrivers u 
    ON u.DriverId = c.DriverId