Avatar of systems_ax
systems_ax
 asked on

SELECT statement with multiple inner joins in visual basic 2005

I am developing with visual basic 2005 and everything was working great until I divided my 1 very large access table into other 5 tables.  I have 2 forms, 1 form is the search form with a datagrid that populates multiple record data.  When I double click on a particular record, the following code executes successfully when I am reading from only 1 table:

 Private Sub dgvLastNames_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvLastNames.CellDoubleClick
        If dgvLastNames.CurrentRow.Index > -1 Then
            Dim editForm As New frmAddClient
            editForm.ClientId = CType(dgvLastNames.CurrentRow.Cells(0).Value.ToString(), Int32)

                     Me.Dispose()
            'If editForm.WindowState = FormWindowState.Minimized Then
            '    editForm.WindowState = FormWindowState.Normal
            'End If
           editForm.ShowDialog()
            RetrievClients()
        Else : MessageBox.Show("please select a row for editing.", "No Row selected", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

    End Sub



Private Sub RetrievClients()
        Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb")

     
       Dim adapter As New OleDbDataAdapter("select * from Clients", conn)
        Dim dt As New DataTable("Clients")
        adapter.Fill(dt)
        dgvLastNames.DataSource = dt
      End Sub

on the form where the record populates executes this code:

   Private Sub RetrievClientsDetails()
       
        Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb")
        Dim command As New OleDbCommand("select * from Clients where ClientId=" & _clientID, conn)
         conn.Open()
        Dim contactreader As OleDbDataReader = command.ExecuteReader
        contactreader.Read()
        Me.txtFirst.Text = contactreader("ClientFirstName").ToString
        Me.txtMiddle.Text = contactreader("ClientMiddleName").ToString
        Me.txtLast.Text = contactreader("ClientLastName").ToString
        Me.txtCompany.Text = contactreader("ClientCompany").ToString
        Me.txtAddress1.Text = contactreader("ClientStreetAddress1").ToString
        Me.txtAddress2.Text = contactreader("ClientStreetAddress2").ToString
        Me.txtID.Text = contactreader("ClientIdNumber").ToString

        Me.txtCity.Text = contactreader("ClientCity").ToString
        Me.txtState.Text = contactreader("ClientState").ToString
        Me.txtPostal.Text = contactreader("ClientPostalCode").ToString
        Me.txtCountry.Text = contactreader("ClientCountry").ToString
        Me.txtDate.Text = contactreader("ClientDateofBirth").ToString
        Me.txtPhone1.Text = contactreader("ClientTelephoneNumberOne").ToString
        Me.txtPhone2.Text = contactreader("ClientTelephoneNumberTwo").ToString
        Me.txtFax.Text = contactreader("ClientFaxNumber").ToString
        Me.txtEmail.Text = contactreader("ClientEmail").ToString
        conn.Close()
           
    End Sub

HOWEVER WHEN I TRY to join multiple table data for 1 client on which I double clicked within the grid it is not working:

this is what I tried for both and replaced the current select statement:

please offer a suggestion.
Dim command As New OleDbCommand("select * from tblClients INNER JOIN tblClientDetails ON tblClients.ClientId = tblClientDetails.ClientId where ClientId=" & _clientID, conn)
 
error that I receive is:
The specified field 'ClientId' could refer to more than one table listed in the FROM clause of your SQL statement.

Open in new window

.NET ProgrammingVisual Basic.NET

Avatar of undefined
Last Comment
systems_ax

8/22/2022 - Mon
Guy Hengel [angelIII / a3]

the problem is the * which will eventually return 2 or more columns with the same name in both tables, ie Clientid.
which is the problem.

so, what you need to do is do something like this, putting the field names explicitly, including putting column alias names ...



Dim command As New OleDbCommand("select c.ClientID, cd.ClientID cdClientID ... from tblClients c INNER JOIN tblClientDetails cd ON c.ClientId = cd.ClientId where c.ClientId=" & _clientID, conn)

Open in new window

systems_ax

ASKER
angelIII,
thank you for replying.
can you please explain why there are multiples of ClientId's, sorry I am just a novice.
thank you
Guy Hengel [angelIII / a3]

>can you please explain why there are multiples of ClientId's,
based on your join condition:
>ON c.ClientId = cd.ClientId
you have the same column name in both tables.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
systems_ax

ASKER
angelIII,
thank you I do not understand what this line means:

Dim command As New OleDbCommand("select c.ClientID, cd.ClientID cdClientID ... ***why is there cd.ClientID and cdClientID.

thank you
Guy Hengel [angelIII / a3]

the cdClientID would be the column alias for the ClientID from table CustomerDetails.
that alias would make sure you get 2 distinct names, while the tables initially have the same column name.
systems_ax

ASKER
angellll,
so,the command will look this way:
Dim command As New OleDbCommand("select c.ClientID, cd.ClientID from tblClients c INNER JOIN tblClientDetails cd ON c.ClientId = cd.ClientId where c.ClientId=" & _clientID, conn)
thank you.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
DelmarIT

Try adding the table name to the ClientId in the where clause
Dim command As New OleDbCommand("select * from tblClients INNER JOIN tblClientDetails ON tblClients.ClientId = tblClientDetails.ClientId where tblClients.ClientId=" & _clientID, conn)

Open in new window

Guy Hengel [angelIII / a3]

>so,the command will look this way:
>Dim command As New OleDbCommand("select c.ClientID, cd.ClientID from tblClients c INNER JOIN tblClientDetails cd ON >c.ClientId = cd.ClientId where c.ClientId=" & _clientID, conn)

no, because you keep then 2 return columns with the same name.

this would work (returning only 1 column with the name ClientID):
Dim command As New OleDbCommand("select c.ClientID from tblClients c INNER JOIN tblClientDetails cd ON c.ClientId = cd.ClientId where c.ClientId=" & _clientID, conn)

and this would work (returning 2 columns, but the second one having originally the same name with a different one -> alias name)
Dim command As New OleDbCommand("select c.ClientID, cd.ClientID as cdClient from tblClients c INNER JOIN tblClientDetails cd ON c.ClientId = cd.ClientId where c.ClientId=" & _clientID, conn)

systems_ax

ASKER
DelmarIT,
works great.  How can I join more tables into the present select command?

thank you.
Your help has saved me hundreds of hours of internet surfing.
fblack61
DelmarIT

You can add more joins to the statement but it will not return rows if one of the tables does not have a match.  This page has a good explanation http://www.w3schools.com/Sql/sql_join.asp
Dim command As New OleDbCommand("select * from tblClients INNER JOIN tblClientDetails ON tblClients.ClientId = tblClientDetails.ClientId INNER JOIN tblClientOrders ON tblClients.ClientId = tblClientOrders.ClientId where tblClients.ClientId=" & _clientID, conn)

Open in new window

systems_ax

ASKER
DelmarIT,
it is not working once I start adding more inner joins.
systems_ax

ASKER
angelIII,
are you familiar with multiple inner joins, I need at least 5 as I am trying to pull data from 5 tables for a client.
Please any ideas.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Guy Hengel [angelIII / a3]

>angelIII,
>are you familiar with multiple inner joins, I need at least 5 as I am trying to pull data from 5 tables for a client.

yes, very.
tip: get the SQL running in sql server directly, best in a stored procedure for example, so that you vb code will just call the procedure with some parameters.
that will make you collect all the benefits:
* rapid development
* quicker code
* smaller code

now, in regards to the multiple joins, you would need to clarify the problem(s) you have.
like, what (error) messages your get with which query...
systems_ax

ASKER
angelIII,
I am working with access 2007 database unfortunately.  I just tried doing an inner join on 3 tables, which works fine IF I ACTUALLY ENTER DATA.  If i try to open a client with no such data, the code breaks: here is my inner join:
 is there a problem with my inner join?
thank you
  Dim command As New OleDbCommand("select * from (tblClients INNER JOIN tblClientDetail ON tblClients.ClientId = tblClientDetail.ClientId) INNER JOIN tblClientDetailOne on tblClients.ClientId=tblClientDetailOne.ClientId where tblClients.ClientId=" & _clientID, conn)

Open in new window

Guy Hengel [angelIII / a3]

>if i try to open a client with no such data, the code breaks
I assume you mean: there is no data returned if there is no data in neither tblClientDetailOne nor tblClientDetail.
in which case, change INNER JOIN into LEFT OUTER JOIN
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
systems_ax

ASKER
angellll,
I have tried outer joining 3 tables with no issues, only when I add one more outer join, my code errors out and says that:
"syntax error in FROM clause"
what Am i doing wrong.
THIS ONE WORKS PERFECT
dim command As New OleDbCommand("select * from (tblClients left outer JOIN tblClientDetail1 ON tblClients.ClientId = tblClientDetail1.ClientId) left outer JOIN tblClientDetail2 on tblClients.ClientId=tblClientDetail2.ClientId
where tblClients.ClientId=" & _clientID, conn)
 
THIS IS HAS SYNTAX ERRORS:
dim command As New OleDbCommand("select * from (tblClients left outer JOIN tblClientDetail1 ON tblClients.ClientId = tblClientDetail1.ClientId) (left outer JOIN tblClientDetail2 on tblClients.ClientId=tblClientDetail2.ClientId) (left outer JOIN tblClientDetail3 on tblClients.ClientId=tblClientDetail3.ClientId) where tblClients.ClientId=" & _clientID, conn)

Open in new window

Guy Hengel [angelIII / a3]

please try to move the " ( " like this:
dim command As New OleDbCommand("select * from (((tblClients left outer JOIN tblClientDetail1 ON tblClients.ClientId = tblClientDetail1.ClientId) left outer JOIN tblClientDetail2 on tblClients.ClientId=tblClientDetail2.ClientId) left outer JOIN tblClientDetail3 on tblClients.ClientId=tblClientDetail3.ClientId) where tblClients.ClientId=" & _clientID, conn)

Open in new window

systems_ax

ASKER
angelIII,
it says that there is "syntax error (missing operator) in my query.  I pasted you code into my program.
thank you
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
Guy Hengel [angelIII / a3]

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
systems_ax

ASKER
angelIII,
you are a genious.  So, I just add an extra "(" to from (((tblClients  as I add more joins?
thank you
Guy Hengel [angelIII / a3]

>So, I just add an extra "(" to from (((tblClients  as I add more joins?
yes, and also () around the ON <condition>, ie ON ( <condition> )
systems_ax

ASKER
thank you so much.
it works great.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23