Skip to content
Advertisement

Comparing multiple tables in Sqlite 3 using python

I am quite new to SQLITE3 as well as python. I a complete beginner in SQLite. I don’t understand much. I am right now learning as a go for my project.I am working on a project where I have one database with about 20 tables inside of it. One table is for user input and the other tables are pre-loaded with values. How can I compare and match which values that are in the pre-loaded table with the user table?? For example:

JavaScript

Now, I want to be able to compare each row in the Pre-Loaded Table to each row in the Users Table. They both have the Barcode column in common to be able to compare. As a result, during the query process, it should check each row:

JavaScript

so when a Barcode, in this case, 1100 doesn’t exist in the Users Table, the code should print: You don’t have all the items for the Pre-Loaded Table. How can I get the code to this?

so far I have this: This code does work by the way.

JavaScript

It prints:

JavaScript

The SQLite code:

JavaScript

It combines the two tables with the Barcode in common and and the corresponding food names and availability. However, If one of the barcode values is not present in the Pre-Loaded table, when I compare how can I go about coding to know that it is not there while still displaying what is there in common between those two tables? It is like checking to see if the tables are identical.

Advertisement

Answer

Perhaps try your luck with LEFT JOIN and a CASE statement.

From sqlite doc

If the join-operator is a “LEFT JOIN” or “LEFT OUTER JOIN”, then after the ON or USING filtering clauses have been applied, an extra row is added to the output for each row in the original left-hand input dataset that corresponds to no rows at all in the composite dataset (if any).

You need the Recipe1 table to be the left-hand table, because you need to select every row in that table. All columns from Users_Food will be null in the extra row. The sample query adds another column “status”, which you can use in the python. With a little rearranging:

JavaScript

In python you might not want to print("You can make: Ham Swiss Omelet") since you won’t know whether that is true until you fetch all the returned rows.

After you get the SQL to return the rows that you want, you can play around with the python to get the desired output.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement