使用内部联接时列表框内容为空

时间:2014-07-23 06:10:58

标签: sql vb.net

我正在尝试使用2个表中的内容填充列表框。当我尝试从任一表中“全选”时,我在列表框中得到结果。当我尝试使用innerjoin查询时,列表框为空。没有错误,只是一个空盒子。要加入的字段是customers.custID = sales.cust_id。我做错了什么?

cust_cn.ConnectionString = "Data Source=localhost;Initial Catalog=tires;Integrated Security=True"
    cust_cn.Open()
    'Dim selectStatement As String = "SELECT * FROM customers as C inner join sales as S on c.custID=s.cust_ID "
    'Dim b As New System.Text.StringBuilder()
    'Dim adpt As New SqlDataAdapter(selectStatement, cust_cn)
    'Dim myDataSet As New DataSet()
    'adpt.Fill(myDataSet)
    'Dim myDataTable As DataTable = myDataSet.Tables(0)
    'Dim tempRow As DataRow
    'For Each tempRow In myDataTable.Rows
    'lstCustSales.Items.Add(tempRow(tempRow("c.first") & tempRow("c.last") & "TIRE ID: " & tempRow("s.tire_id") & "QTY: " & tempRow("s.qty") & tempRow("s.notes")))
    'Next


    'Dim selectStatement As String = "select * from customers"
    'Dim b As New System.Text.StringBuilder()
    'Dim adpt As New SqlDataAdapter(selectStatement, cust_cn)
    'Dim myDataSet As New DataSet()
    'adpt.Fill(myDataSet, "customer_data")
    'Dim myDataTable As DataTable = myDataSet.Tables(0)
    'Dim tempRow As DataRow
    'For Each tempRow In myDataTable.Rows
    '    lstCustSales.Items.Add(tempRow("custphone") & "   " & tempRow("last") & tempRow("first") & " " & tempRow("address") & "   " & tempRow("zip") & temprow("custid"))
    'Next

    Dim selectStatement As String = "select * from sales"
    Dim b As New System.Text.StringBuilder()
    Dim adpt As New SqlDataAdapter(selectStatement, cust_cn)
    Dim myDataSet As New DataSet()
    adpt.Fill(myDataSet, "sales_data")
    Dim myDataTable As DataTable = myDataSet.Tables(0)
    Dim tempRow As DataRow
    For Each tempRow In myDataTable.Rows
        lstCustSales.Items.Add(tempRow("date") & "   " & tempRow("cust_id") & tempRow("tire_id") & " " & tempRow("qty") & "   " & tempRow("total") & tempRow("notes"))
    Next

当我去管理工作室并输入时:

SELECT * FROM customers as C inner join sales as S on c.custID=s.cust_ID where c.custphone=7146511734

我从两个表中获得了完整的结果,仅限于我的手机#(正确/预期的结果)

1 个答案:

答案 0 :(得分:0)

我很长时间没有使用VB数据集,客户端数据集如何解析每个列名与在管理工作室中完成的方式之间存在差异。基本上在Management Studio中我假设它纯粹是一个字符串输出,并且不需要引用列名。如果两个表中的字段都具有相同的名称,则可能会导致问题。

我建议您在select语句中明确说明您实际想要从查询中检索的字段,而不是使用“ SELECT * ”。无论如何,这是一种很好的做法,因为返回额外的字段会浪费资源,特别是如果有BLOB字段

SELECT c.first, c.last, s.tire_id, s.qty, s.notes

实际上再次查看你的代码 - 你有一个tempRow,正在寻找一个名为tempRow(“...”)的列

lstCustSales.Items.Add(tempRow(tempRow("c.first") & tempRow("c.last") & "TIRE ID: " & tempRow("s.tire_id") & "QTY: " & tempRow("s.qty") & tempRow("s.notes")))