Suppose I have a query that returns the total monthly sales of individual products in my database:
product = input("Enter product column to search") milkOptions = input("Enter milkOptions column to search") size = input("Enter size to search") import sqlite3 conn=sqlite3.connect("system.db") cur=conn.cursor() sql =""" select sum(quantity*price), strftime("%m-%Y", orderDate) as month from customerOrders WHERE product = ? and milkOptions = ? and size = ? group by orderDate"""
Is there a way to query various levels of specificity without creating many similar queries. For instance, If i enter Espresso for the product, leave out the milkoptions entry, and enter small for size, could I return all Small Espresso sales. Vice versa for leaving out and entering other options.
Here is my database:
+---------+-----------+--------+-------------+------------+----------+-------+------------+ | orderid | product | size | milkOptions | orderDate | quantity | price | customerid | +---------+-----------+--------+-------------+------------+----------+-------+------------+ | 1 | Espresso | Small | Soya | 2019-10-29 | 1 | 1.0 | 1 | | 2 | Cappucino | Small | SemiSkimmed | 2019-10-29 | 1 | 1.0 | 1 | | 3 | Cappucino | Small | SemiSkimmed | 2019-10-29 | 1 | 1.0 | 1 | | 4 | Cappucino | Medium | SemiSkimmed | 2019-10-29 | 1 | 1.0 | 1 | +---------+-----------+--------+-------------+------------+----------+-------+------------+
Advertisement
Answer
Pass an additional flag parameter 0
or 1
for each of the columns, like:
WHERE (product = ? OR 0 = ?) AND (milkOptions = ? OR 0 = ?) AND (size = ? OR 0 = ?)
- When you pass
0
for theproduct
‘s flag parameter (and anything not null for the columnproduct
) the condition will evaluate toTRUE
which is equivalent to not setting a condition for the columnproduct
. - When you pass
1
for theproduct
‘s flag parameter and'someproduct'
for the columnproduct
then the condition is equivalent toproduct = 'someproduct'
.