0

I am creating a new table with data from another table. I would like to combine the values from an Income_Ledger table as well as an Expenditure_Ledger table, with a WHERE condition, into a new table.

I can successfully add the values if only using one of the tables, but I can’t seem to write the SQL syntax to perform the input from both tables. i.e. the AS SELECT, FROM, WHERE works if only using one of the two tables.

Thanks for any help

MySQL (ver 14.14 Distr 5.7.23)

# bank in for below gives strings of: B1 and B2
for bank in Bank_Account_Code:
    with engine.connect() as con:
        con.execute('''
        DROP TABLE IF EXISTS '''+bank+''';''')
        con.execute('''
        CREATE TABLE IF NOT EXISTS '''+bank+'''
        AS SELECT id,Date,CR
        FROM Income_Ledger
        WHERE DR_code="'''+bank+'''"

        AS SELECT id,Date,DR
        FROM Expenditure_Ledger
        WHERE CR_code="'''+bank+'''"

        ORDER BY Date
        ;''')

enter image description here

2
  • 1
    Creating a separate table for each entity is a really bad idea under most circumstances. Please explain what problem you are trying to do. Commented May 5, 2020 at 10:47
  • Create a view instead. No copying of data needed, will always be up-to-date. Commented May 5, 2020 at 10:48

1 Answer 1

1

You cant simply select two tables and put them into one. Depending on how you want to combine the data you can either JOIN the tables, or use UNION. Seeing the CR_code in the two tables, UNION is your best bet for this situation.

https://www.w3schools.com/sql/sql_union.asp https://www.w3schools.com/sql/sql_join.asp

Sign up to request clarification or add additional context in comments.

1 Comment

for bank in Bank_Account_Code: with engine.connect() as con: con.execute(''' DROP TABLE IF EXISTS `'''+bank+'''` ;''') con.execute(''' CREATE TABLE IF NOT EXISTS '''+bank+''' SELECT id, Date, DR_code, DR, CR, CR_code FROM Income_Ledger WHERE DR_code="'''+bank+'''" UNION ALL SELECT id, Date, DR_code, DR, CR, CR_code FROM Expenditure_Ledger WHERE CR_code="'''+bank+'''" ORDER BY DATE ;''')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.