2013-04-17 45 views
1

我有一個返回行比我預想的更多的是SQL Server查詢:SQL Server查詢返回更多的行比預期

select 
    b.isbn, l.lend_no, s.first_name 
from 
    dbo.books b, dbo.lending l, dbo.students s 
where 
    (l.act between '4/16/2013' and '4/16/2013') 
    and (l.stat ='close')` 

我想要做的就是這本書返回日期isbnlend_nostudent name之間給定的日期和借出狀態是封閉的,我的貸款表只有2個貸款返回給定的日期,但查詢給我304行

+0

你能提供的表格是什麼樣子的樣本。 – James

+3

沒有'JOIN'條件? – shahkalpesh

+1

那是因爲你是'CROSS JOIN''三個表'dbo.books b,dbo.lending l,dbo.students s'。改爲加入它們。請張貼表格的結構。 –

回答

2

你'並不是在表格之間定義任何加入條件,因此您將獲得笛卡爾產品。

嘗試這樣代替:

SELECT 
    b.isbn, l.lend_no, s.first_name 
FROM 
    dbo.books b 
INNER JOIN 
    dbo.lending l ON l.Book_id = b.Book_id -- just guessing here 
INNER JOIN 
    dbo.students s ON l.student_id = s.student_id -- just guessing here 
WHERE 
    l.act BETWEEN '20130416' AND '20130416' 
    AND l.stat = 'close' 

定義聯接條件需要 - 我不知道你的表,你必須找出哪些列的兩個表分別鏈接。

我還使用了正確的ANSI JOIN語法 - 不要只列出一串以逗號分隔的表,這些表在20年前已經被SQL標準踢出(SQL 1992)。

另外:我會一直使用的ISO-8601的日期格式YYYYMMDD是安全的 - 這是唯一格式上的SQL Server的所有版本,並與所有的語言,地區和日期格式設置工作。

3

您當前的查詢從三個表中獲取笛卡爾積,導致檢索意外的結果。您需要定義關係或表應該如何加入,例如

select b.isbn, l.lend_no, s.first_name 
from dbo.books b 
     INNER JOIN dbo.lending l 
      ON c.Colname = l.ColName -- << define condition here 
     INNER JOIN dbo.students s 
      ON ......    -- << define condition here 
where l.act between '4/16/2013' and '4/16/2013' and 
     l.stat ='close' 

爲了進一步獲得更多的知識有關加入,請訪問以下鏈接:

+0

謝謝JW ,, Link對我很有用 – Roshan