如何使用MySQL中的两个表条件

时间:2014-11-18 09:28:54

标签: mysql vb.net

任何人都可以帮我这个吗?我想要发生的是,如果表1(员工)中存在该值,则它将检查表2(移动列表)是否存在于那里。这是代码:

 Private Sub TextBox_IDNumber_LostFocus(sender As Object, e As EventArgs) Handles TextBox_IDNumber.LostFocus
    Mysqlconn = New MySqlConnection
    Mysqlconn.ConnectionString = "server=localhost;userid=root;password=12345;database=my_db"
    Dim READER As MySqlDataReader
    Dim READER2 As MySqlDataReader
    Dim _isFound As Boolean = False
    Dim _isExist As Boolean = False
    Try
        Mysqlconn.Open()
        Dim empmr As String
        Dim empml As String
        Dim fn1 As String
        Dim fn2 As String
        Dim ln1 As String
        Dim ln2 As String
        empmr = "Select * from my_db.employee where IDNumber ='" & TextBox_IDNumber.Text & "'"
        empml = "Select * from my_db.mobilelist where IDNumber = '" & TextBox_IDNumber.Text & "' AND DateAssigned is not Null AND DateReturned is Null"
        Command = New MySqlCommand(empmr, Mysqlconn)
        READER = Command.ExecuteReader
        While READER.Read()
            _isFound = True
            fn1 = READER.GetString("FirstName")
            ln1 = READER.GetString("LastName")
        End While

        If _isFound Then
            TextBox_FirstName.Text = fn1
            TextBox_LastName.Text = ln1

        ElseIf Not _isExist Then
            MessageBox.Show("Record Not Found in Master Data")
            TextBox_IDNumber.Clear()
            TextBox_FirstName.Clear()
            TextBox_LastName.Clear()
            TextBox_IDNumber.Focus()
        End If

    Catch ex As MySqlException
        MessageBox.Show("Error!")
    Finally
        Mysqlconn.Dispose()
    End Try
End Sub

1 个答案:

答案 0 :(得分:0)

假设您使用表员工 MobileList 之间有相应的主键外键关系此查询用于查找员工 MobileList 表中的记录:

Dim myQuery as string
myQuery = "SELECT FirstName, LastName, MobileNumber 
           FROM Employee 
           JOIN MobileList
           ON Employee.IDNumber=MobileList.IDNumber   
           WHERE Employee.IDNumber=@ID"

注意:您应该重命名移动列表上的 IDNumber 列,以避免混淆。

您还应该使用Using语句改进对数据库的访问,并利用参数来阻止SQL注入:

Using myConn As New SqlConnection("Your connection string")
     myConn.Open()
     Using myCmd As New SqlCommand(myQuery, myConn)
         myCmd.Parameters.AddWithValue("@ID", "Your ID value")
         Using myReader As SqlDataReader = myCmd.ExecuteReader()
             If myReader.HasRows Then
                 'There are mobile numbers issued to that ID'
                 Do While myReader.Read()
                     'Iterate through all existing records'
                 Loop
             Else
                 'There are no mobile numbers issued to that ID'
             End If
         End Using
     End Using
 End Using

请注意,这会为您提供特定员工的手机号码,但不会告诉您特定员工是否存在。