2010-04-01 132 views
2

我試圖從最新的現金記錄中抓取所有字段,然後從相關的TransactionInfo記錄中獲取所有字段。我不能完全得到這個工作:SQL加入聲明問題

select t.*, top 1 c.* from Cash c 
inner join TransactionInfo t 
on c.TransactionID = t.id 
order by c.createdOn desc 
+0

CreatedOn列屬於哪個表? – 2010-04-01 13:56:19

+0

對不起,發佈錯誤。現在更新。 – PositiveGuy 2010-04-01 14:09:32

回答

1

那是什麼top 1在那裏做?如果你只想要一個行則TOP(1)必須是第一位的:

SELECT TOP(1) t.*, c.* 
FROM Cash c 
INNER JOIN TransactionInfo t 
ON c.TransactionID = t.id 
ORDER BY c.createdOn DESC 
+1

頂部是因爲我想只抓住最新條目插入..不知道它的ID – PositiveGuy 2010-04-01 13:53:06

+0

是啊我看你現在說什麼。如果我只想要最新的記錄,而不是所有的記錄。我只想看到一個結果,那就是根據CreatedOn插入到現金中的最新記錄。 – PositiveGuy 2010-04-01 13:54:43

+0

每個交易的現金每個最新條目? – 2010-04-01 13:54:48

2
select top 1 * 
from Cash c 
inner join TransactionInfo t on c.TransactionID = t.id 
order by createdOn desc 
+0

,但也會抓住結果集中TransactionInfo的所有字段?我需要看到兩組字段。 – PositiveGuy 2010-04-01 13:52:48

+1

+1 - 我認爲這是OP之後的事情(即仍然需要TOP 1,這只是在錯誤的地方) – AdaTheDev 2010-04-01 13:52:50

+1

@coffeeaddict - 你試過運行這個查詢嗎?從你的評論中,它確實聽起來像這是你想要的。你可以嘗試一下,並澄清它是否(或不)做你想做的事情? – AdaTheDev 2010-04-01 14:08:50

0

選擇T。 ,c。 從(選擇頂部1 *從由createdOn降序 現金順序)C 內上c.TransactionID = t.id 順序加入TransactionInfo噸 通過createdOn降序

不;噸使用select *尤其是與一個連接,它浪費了服務器資源。

0
SELECT c.*, t.* FROM cash c, transactioninfo t 
WHERE c.infoid = t.id AND c.createdOn = (SELECT max(createdOn) FROM cash WHERE infoId = t.id) ORDER BY transactiontabledate desc 

您需要從每個transactionId的現金錶中查找帶有最新日期的記錄,並使用它在您的查詢中進行過濾。