2016-09-19 69 views
0

我試圖在我的數據庫中查詢表來填充表單上的下拉字段。 我希望Field1作爲顯示,Field2作爲我插入的值。用於填充下拉字段的SQL查詢

select '[CategoryName]','[CatID]' from BND_ListingCategories 

上述查詢只是將[CategoryName]填充爲下拉列表中的所有值。

現在確定我做錯了什麼。


UPDATE:

嗨, 所以我想我明白了爲什麼我的查詢不工作我需要添加一個連接語句作爲(類別名稱)字段是另一個表。

即使如此,通過此更新的查詢,我現在得到一個錯誤 錯誤:不明確的列名'CatID'。

select [CategoryName],[CatID] from BND_ListingCategories 
inner join BND_Listing 
on BND_ListingCategories.CatID=BND_Listing.CatID 
where LID=1 

更新2

好了所以我進取掏出傻瓜得心應手醇SQL。

通過編輯我的查詢,解決了我的含糊問題。

select c.CategoryName, l.CatID 
from BND_ListingCategories AS c INNER JOIN BND_Listing as l 
on c.CatID = l.CatID 

得到它只是工作想看看我怎麼能按字母順序排序的類別名稱

+0

你在用什麼語言? C#/ ASP.NET,PHP,別的東西?您可能也想分享該代碼。 – zedfoxus

+0

這是我相信用C#編寫的DNN平臺,但我使用的是插件。我不確定它是用什麼編碼的,但我猜C#也 – UserSN

回答

3

從列名中刪除單引號。

select [CategoryName],[CatID] from BND_ListingCategories 

如果您想對類別名稱進行排序,請使用ORDER BY。

select c.CategoryName, l.CatID 
    from BND_ListingCategories as c 
     INNER JOIN BND_Listing as l 
      on c.CatID = l.CatID 
    Order by c.CategoryName 
2

你的語法只是一點點關閉所有。刪除引號,然後您將返回查詢結果。

select [CategoryName],[CatID] from BND_ListingCategories 

您應該只需要修改選擇列表以指定要從中拉出該列的表格。您可能需要在選擇語句中的兩列中執行此操作。

編輯新的更新問題:

select [CategoryName], BND_Listing.[CatID] from BND_ListingCategories 
inner join BND_Listing 
on BND_ListingCategories.CatID=BND_Listing.CatID 
where LID=1 
+0

當我嘗試使用該語法時,我收到一條錯誤消息。 初始化表單失敗:關鍵字'from'附近的語法不正確。 – UserSN

+0

你能發佈與問題相關的所有代碼嗎?我有一個感覺,這個問題是在早期的鏈條。 – Zi0n1

+0

選擇[CategoryName],BND_ListingCategories。[CatID] from BND_ListingCategories inner join BND_Listing on BND_ListingCategories.CatID = BND_Listing.CatID 其中LID = 1 – Zi0n1

0
select distinct c.CategoryName, l.CatID 
from BND_ListingCategories AS c INNER JOIN BND_Listing as l 
on c.CatID = l.CatID 
ORDER BY CategoryName ASC 

這引起了我的下拉工作。謝謝你們的幫助。讓我看在正確的地方!