Using Joins to fetch specific sets of data

I am trying to print a trial balance with data that is received from 3 different MySQL database tables.

The structure is as follows:

[PostGL] : AccountLink, Debit and Credit

[GLAccountTypes] : AccountType , Description

[Accounts] : AccountLink , AccountType , Account Number

I am trying to use the following SELECT query to fetch the data as such:

Views.py:

def Kyletrb(request):
    trialBalance =  'SELECT  [dbo].[PostGL].[Debit] , [dbo].[PostGL].[Credit], [dbo].[Accounts].[Master_Sub_Account] ,[dbo].[_etblGLAccountTypes].[cAccountTypeDescription] FROM [Kyle] INNER JOIN [Kyle].[dbo].[_etblGLAccountTypes] ON [Kyle].[dbo].[PostGL].[AccountLink] = SELECT [Kyle].[dbo].[Accounts].[AccountLink] INNER JOIN [Kyle].[dbo].[PostGL] ON [Kyle].[dbo].[Accounts].[iAccountType] =   [dbo].[_etblGLAccountTypes].[idGLAccountType] '

    cursor.execute(trialBalance);
    trialBalanceFinal = [tup[0] for tup in cursor.fetchall()]

    return render(request , 'main/Kyletrb.html' , {'trialBalance' : trialBalanceFinal} )

Error Message:

NameError at /Kyletrb name ‘cursor’ is not defined Request Method: GET Request URL: http://localhost:8000/Kyletrb Django Version: 3.2 Exception Type: NameError Exception Value:
name ‘cursor’ is not defined Exception Location: C:UsersKylePOGDocumentsGMA ProgrammingaccConnectmainviews.py, line 26, in Kyletrb Python Executable: C:UsersKylePOGAppDataLocalProgramsPythonPython39python.exe Python Version: 3.9.4 Python Path:
[‘C:UsersKylePOGDocumentsGMA ProgrammingaccConnect’, ‘C:UsersKylePOGAppDataLocalProgramsPythonPython39python39.zip’, ‘C:UsersKylePOGAppDataLocalProgramsPythonPython39DLLs’, ‘C:UsersKylePOGAppDataLocalProgramsPythonPython39lib’, ‘C:UsersKylePOGAppDataLocalProgramsPythonPython39’, ‘C:UsersKylePOGAppDataLocalProgramsPythonPython39libsite-packages’] Server time: Tue, 31 Aug 2021 11:00:05 +0000

What I expect the output to be : enter image description here

Is there anyway to use the JOIN function in the SQL query to fetch the Account Number , Description , Credit & Debit where the accountLink and accountTypes Match

Answer

You can simply join all three tables like so:

SELECT t1.AccountNumber, t2.Description, t3.Credit, t3.Debit
FROM Accounts t1 
   INNER JOIN GLAccountTypes t2
      ON t1.AccountType = t2.AccountType
   INNER JOIN PostGL t3
      ON t1.AccountLink = t3.AccountLink