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:
Users Table:
Barcode: Item:
1234 milk
4321 cheese
5678 butter
8765 water
9876 sugar
Pre-Loaded Table:
Barcode: Availability:
1234 1
5678 1
9876 1
1111 1
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:
1234 - milk - 1 (those columns are equal )
5678 - butter - 1 ( those columns are equal)
9876 - sugar - 1 (those columns are equal)
1100 - - 1 ( this barcode does not exist in the Users Table)
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.
import sqlite3 as sq
connect = sq.connect('Food_Data.db')
con = connect.cursor()
sql = ("SELECT Users_Food.Barcode, Users_Food.Item, Recipe1.Ham_Swiss_Omelet FROM Users_Food INNER JOIN Recipe1 ON Users_Food.Barcode = Recipe1.Barcode WHERE Recipe1.Ham_Swiss_Omelet = '1'")
con.execute(sql)
data = con.fetchall()
print("You can make: Ham Swiss Omelet")
formatted_row = '{:<10} {:<9} {:>9} '
print(formatted_row.format("Barcode", "Ingredients", "Availability"))
for row in data:
print(formatted_row.format(*row))
#print (row[:])
#connect.commit()
It prints:
You can make: Ham Swiss Omelet
Barcode Ingredients Availability
9130849874 butter 1
2870896881 eggs 1
5501066727 water 1
1765023029 salt 1
9118188735 pepper 1
4087256674 ham 1
3009527296 cheese 1
The SQLite code:
sql = ("SELECT Users_Food.Barcode, Users_Food.Item, Recipe1.Ham_Swiss_Omelet FROM Users_Food INNER JOIN Recipe1 ON Users_Food.Barcode = Recipe1.Barcode WHERE Recipe1.Ham_Swiss_Omelet = '1'")
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.
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:
SELECT Users_Food.Barcode, Users_Food.Item, Recipe1.Ham_Swiss_Omelet,
CASE WHEN (Users_Food.Barcode is null then 'You cannot make this recipe' else ' ' END as status
FROM Recipe1
LEFT JOIN Users_Food ON Users_Food.Barcode = Recipe1.Barcode
WHERE Recipe1.Ham_Swiss_Omelet = '1'
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.
Related
I have a table containing full of movie genre, like this:
id | genre
---+----------------------------
1 | Drama, Romance, War
2 | Drama, Musical, Romance
3 | Adventure, Biography, Drama
Im looking for a way to get the most common word in the whole genre column and return it to a variable for further step in python.
I'm new to Python so I really don't know how to do it. Currently, I have these lines to connect to the database but don't know the way to get the most common word mentioned above.
conn = mysql.connect()
cursor = conn.cursor()
most_common_word = cursor.execute()
cursor.close()
conn.close()
First you need get list of words in each column. i.e create another table like
genre_words(genre_id bigint, word varchar(50))
For clues how to do that you may check this question:
SQL split values to multiple rows
You can do that as temporary table if you wish or use transaction and rollback. Which one to choose depend of your data size and PC on which DB running.
After that query will be really simple
select count(*) as c, word from genre_word group by word order by count(*) desc limit 1;
You also can do it using python, but if so it will not be a MySQL question at all. Need read table, create simple list of word+counter. If it new, add it, if exist - increase counter.
from collections import Counter
# Connect to database and get rows from table
rows = ...
# Create a list to hold all of the genres
genres = []
# Loop through each row and split the genre string by the comma character
# to create a list of individual genres
for row in rows:
genre_list = row['genre'].split(',')
genres.extend(genre_list)
# Use a Counter to count the number of occurrences of each genre
genre_counts = Counter(genres)
# Get the most common genre
most_common_genre = genre_counts.most_common(1)
# Print the most common genre
print(most_common_genre)
I use a program that outputs data into an sqlite database. For my needs, the data in the existing database is not formatted well, so I am doing some preprocessing which will be inserted into a new table. See below:
Input (there are more columns not shown, and this table is actually a join of three, if that matters)
First Name
Last Name
State
Start Time
Stop Time
Bill
Smith
NV
0
5
Bill
Smith
NV
12
15
Bill
Smith
NV
7
8
Bill
Smith
NV
45
47
Maggie
Tangerine
MI
3
7
Maggie
Tangerine
MI
68
90
Bill
Smith
NV
60
66
Desired output
First Name
Last Name
Times
Bill
Smith
np.array(0,5,12,15,7,8,45,47,60,66)
Maggie
Tangerine
np.array(3,7,68,90)
Right now what I tried first was a query to pull the data for a specific name before inserting into the new table:
df = pd.read_sql_query('''
SELECT StartTime,StopTime
FROM Input
INNER JOIN Input1
ON ...
INNER JOIN Input2
ON ...
WHERE FirstName = ?
LastName = ?
State = ?
''', conn, params=(first,last,state))
np.concat(np.unique(df[0].values.flatten()),np.unique(df[1].values.flatten()))
This is going to be really terrible for efficiency, since the query for one set of names takes just slightly less than a query for all the names. Would it be better to try and pull the times for a specific name from the pandas dataframe? Is there some other way to do this I am not thinking of?
yeah, i would look into trying to query all the data without a where clause specifying the name, state and add a group by claus at the end.
"Group by firstname, lastname, state"
I'm currently writing an rpg game in python that uses a mysql database to store info on players. However, I've come across a problem.
Sample Code of How Database has been Set Up:
playerinfo Table
userID | money | xp |
1 | 200 | 20 |
2 | 100 | 10 |
I'm trying to select the amount of money with only the value. My select query right now is
SELECT money FROM playerinfo WHERE id = 1
The full code/function for collecting selecting the info is
def get_money_stats(user_id):
global monresult
remove_characters = ["{", "}", "'"]
try:
with connection.cursor() as cursor:
monsql = "SELECT money FROM players WHERE userid = %s"
value = user_id
cursor.execute(monsql, value)
monresult = str(cursor.fetchone())
except Exception as e:
print(f"An error Occurred> {e}")
CURRENT OUTPUT:
{'money': 200}
DESIRED OUTPUT:
200
Basically, all I want to select is the INT/DATA from the player's row (identified by unique userid). How do I do that? The only solution I have is to replace the characters with something else but I don't really want to do that as it's incredibly inconvenient and messy. Is there another way to reformat/select the data?
It seems like that fetching one row gives you a dictionary of the selected columns with its values, which seems the correct approach to me. You should simply access the dictionary with the column that you want to retrieve:
monresult = cursor.fetchone()['money']
If you don't want to specify again the column (which you should) you could get the values of the dictionary as a list and retrieve the first one:
monresult = list(cursor.fetchone().values())[0]
I do not recommend the last approach because it's heavily dependent on the current status of the query and it may have to change if the query is changed.
I'm trying to create a SELECT statement that selects rows where NAME is max. 5 characters and the . is in the NAME.
I only want the first, so I'm including a LIMIT 1 to the statement.
I have worked with the following
searchstring = "."
sql = "SELECT * FROM Table WHERE NAME LIKE %s LIMIT 1"
val = (("%"+searchstring+"%"),)
cursor.execute(sql, val)
But I'm not sure how to incorporate the length of NAME in my statement.
My "Table" is as follows:
ID NAME
1 Jim
2 J.
3 Jonathan
4 Jack M.
5 M.S.
So based on the table above, I would expect row 2 and 5 to be selected.
I could select all, and loop through them. But as I only want the first, I'm thinking I would prefer a SQL statement?
Thanks in advance.
You can use CHAR_LENGTH function along with LIKE:
SELECT * FROM Table WHERE name LIKE '%.%' AND CHAR_LENGTH(name) <= 5 LIMIT 1
Try LEN()
Select LEN(result string);
This will return the length of string. but this will count spaces also. Try removing it with LTRIM().
Oracle SQL
SELECT * FROM Table WHERE name LIKE '%.%' AND LENGTH(name) < 6 and rownum < 2
Base on the sql language(oracle, mysql, sql server, etc) use
length() or char_length()
rownum or limit
I am learning SQL-Python using SQLAlchemy and will appreciate much help on this.
I have 3 tables,
Table 1 (Actors) : nconst (primary key), names
Table 2 (Movies) : tconst (primary key) , titles
Table 3 (Junction table) : nconst (from Actors table) , tconst(from Movies table)
I am trying to obtain 10 rows of actors that acted in particular movies. Hence I am trying to do an inner join of Actors on Junction table (using nconst) and then another inner join onto Movies table.
In SQL, this means
FROM principals INNER JOIN actors
ON principals.nconst=actors.nconst INNER JOIN
movies ON principals.tconst=movies.tconst
In SQLAlchemy, my current code is:
mt = list(session.query(Movies, Principals, Actors).select_from(
join(Movies, Principals, Movies.tconst == Principals.tconst)
.join(Actors, Principals, Actors.nconst == Principals.nconst
).with_entities(
Movies.title, # Select clause
))
Alternatively, I am trying
from sqlalchemy.orm import join
mv = list(session.query(Actors).select_from(
join(Movies, Principals, Actors, Movies.tconst == Principals.tconst,
Actors.nconst == Principals.nconst) # Join clause
).with_entities(
Actors.name, # Select clause
Movies.title,
))
mv
The error I am getting is an Attribute Error, "Actor type object 'Actors' has no attribute '_from_objects'
Appreciate much help on this. Thank you very much.