2013-09-26 109 views
0

請幫助我,下面是我的sql查詢。當我執行它時,結果是什麼都沒有。SQL Server加入3表

SELECT tblclientinfo.acctnum, 
     tblclientinfo.fname, 
     tblclientinfo.fname, 
     tblreservation.unitnum, 
     tblbillingsched.billnum, 
     tblbillingsched.duedate, 
     tblbillingsched.monthlyamort, 
     tblbillingsched.totalbalance 
FROM tblclientinfo 
     JOIN tblreservation 
     ON tblclientinfo.acctnum = tblreservation.reservationnum 
     JOIN tblbillingsched 
     ON tblreservation.reservationnum = tblbillingsched.accountnum 
WHERE tblbillingsched.accountnum = 'C0000000021' 
     AND tblbillingsched.duedate BETWEEN '1/1/2014' AND '1/30/2014' 

這裏是我的表:

tblClientInfo, pk = acctNum 
tblReservation, pk = ReservationNum, fk = accountNum 
tblBillingSched, pk = ID, fk = accountNum 
+0

您確定您的數據符合這些過濾條件嗎? – Shawn

+0

感謝你們的及時回覆,但結果仍然是空的。我仔細檢查每個表,他們都有數據。我認爲我的PK和FK是問題,但我不知道如何解決它。請看我的桌子關係圖。 [鏈接](http://farm6.staticflickr.com/5520/9950519065_06207ec31e_z.jpg) – Sishan

回答

1

我認爲你正在尋找...

SELECT tblclientinfo.acctnum, 
     tblclientinfo.fname, 
     tblclientinfo.fname, 
     tblreservation.unitnum, 
     tblbillingsched.billnum, 
     tblbillingsched.duedate, 
     tblbillingsched.monthlyamort, 
     tblbillingsched.totalbalance 
FROM tblclientinfo 
     JOIN tblreservation 
     ON tblclientinfo.acctnum = tblreservation.accountnum 
     JOIN tblbillingsched 
     ON tblclientinfo.acctnum = tblbillingsched.accountnum 
WHERE tblbillingsched.accountnum = 'C0000000021' 
     AND tblbillingsched.duedate BETWEEN '1/1/2014' AND '1/30/2014' 

See a demo

+0

@harifx,我的tblbillingsched.duedate數據類型僅爲日期。 – Sishan

+0

這是你的第999個答案:D你發佈的下一個答案是你的第1000個 – Doorknob

+0

@ Doorknob [這是#1000](http://stackoverflow.com/questions/19095318/row-number-over-where-rownumber-between ) – Kermit

0

你先加入是錯誤的。在表tblReservation中,foreignkey是accountNum,您使用字段reservationnum進行加入。 的代碼應該是這樣的:

SELECT tblclientinfo.acctnum, 
    `tblclientinfo.fname, 
    tblclientinfo.fname, 
    tblreservation.unitnum, 
    tblbillingsched.billnum, 
    tblbillingsched.duedate, 
    tblbillingsched.monthlyamort, 
    tblbillingsched.totalbalance 
FROM tblclientinfo 
    JOIN tblreservation 
    ON tblclientinfo.acctnum = tblreservation.accountNum 
    JOIN tblbillingsched 
    ON tblreservation.reservationnum = tblbillingsched.accountnum 
WHERE tblbillingsched.accountnum = 'C0000000021' 
     AND tblbillingsched.duedate BETWEEN '1/1/2014' AND '1/30/2014' 
0

是一個DUEDATE日期時間字段請嘗試以下,看看它的工作原理:

CAST(tblbillingsched.duedate AS DATE)之間的 '2014年1月1日' AND '2014年1月30日'

退房這個職位更詳細的討論:

how to query Datetime object by date?

0

(題外話和probab LY沒有答案,但我認爲值得一提的)

這樣做的更安全的形式:

tblbillingsched.duedate BETWEEN '1/1/2014' AND '1/30/2014' 

是這樣的:

tblbillingsched.duedate >= '20140101' AND 
tblbillingsched.duedate <'20140130' 

陳述這樣'20140130'日期是明白無誤的。