SQL - select distinct

有些话、适合烂在心里 提交于 2019-12-23 06:23:02

问题


I used the select disctinct statement with 2 fields from my sql database table. Here is my code.

myCommand = New SqlCommand("SELECT DISTINCT Author FROM tblBook UNION SELECT DISTINCT BookCode FROM tblBook",myConnection)
 myAdapter = New SqlDataAdapter(myCommand)
 myAdapter.Fill(myDataSet, "tblBook")
 cboAuthor.DataSource = myDataSet.Tables(0)
 cboAuthor.DisplayMember = "Author"
 cboAuthor.DisplayValue = "BookCode"

and it generates error : cannot bind to the new member. Parameter name:value. Please help


回答1:


you have selected only one column in your sql statement, Author. BookCode isn't present so it won't be in the dataset either.

Include the BookCode in the Sql Statement and it will be fixed




回答2:


Maybe you are looking for

SELECT DISTINCT Author, Bookcode FROM tblBook

Union is used to merge rows not columns..

So your query returns a single column where you have all the autors (distinct) followed in the same column by rows of all the bookcodes (distinct as well).




回答3:


A UNION operation does not work in this way.

You want a recordset containing two columns - Authors and BookCodes so you are going to need a query something like:

 SELECT DISTINCT Author, BookCode FROM tblBook



回答4:


You make a query of two distinct things.

You either want to...

  1. Get the author of each book. In that case have to make a query joining the tables, so union is not an option

  2. You indeed need the result as one column, in that case give the column an alias and bind the alias

    SELECT DISTINCT Author AS mycolumn FROM tblBook UNION SELECT DISTINCT BookCode AS mycolumn FROM tblBook



来源:https://stackoverflow.com/questions/6571485/sql-select-distinct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!