Select语句VB导致数据网格重复

时间:2014-01-20 16:57:26

标签: sql vb.net ms-access

我使用的是Access数据库,我相信问题出在我的SQL语句中。我有一个关系数据库,有两个表 -

StaffDetails [columns(
StaffID, 
FirstName, 
LastName)] 

StaffTraining [columns(
StaffID, 
Month)]. 

我有一个组合框(cbMonth),并且如果用户选择“1月”,则依赖于选择的月份,然后我希望数据网格(DGTraining)显示名字和姓氏ID在所选月份内的员工。很抱歉,如果这不是最明确的解释,希望我的代码能让我的问题更加清晰:

Dim SqlQuery As String = "SELECT [StaffDetails.StaffID], [StaffDetails.FirstName], [StaffDetails.LastName], [StaffTraining.StaffID] FROM [StaffDetails], [StaffTraining] WHERE StaffTraining.TrainingMonth='" & cbMonth.Text & "'"
    Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
    Dim ds As DataSet = New DataSet
    da.Fill(ds, "Training")
    Dim dt As DataTable = ds.Tables("Training")

    With DGTraining
        .AutoGenerateColumns = True
        .DataSource = ds
        .DataMember = "Training"
    End With

2 个答案:

答案 0 :(得分:1)

您错过了加入并且正在进行交叉加入。 2种寻址方式:

FROM [StaffDetails] inner join [StaffTraining] on  [StaffDetails].staffID = [StaffTraining].staffID

这是更常见且更易于阅读的连接逻辑。你可以添加到你的where子句(旧方法,更难阅读,而不是普遍接受:

...where [StaffDetails].staffID = [StaffTraining].staffID and ...

答案 1 :(得分:0)

你的上一条评论需要修改这样......

Dim SqlQuery As String = "SELECT [StaffDetails.StaffID], [StaffDetails.FirstName],
[StaffDetails.LastName], FROM [StaffDetails]
INNER JOIN [StaffTraining] ON [StaffDetails].StaffID = [StaffTraining].StaffID
WHERE [StaffTraining].TrainingMonth='" & cbMonth.Text & "'"

另外......取决于您如何设置cbMonth,您可能需要cbMonth.SelectedValue或cbMonth.SelectedText