How to query 4 tables in sqlite3 in python? - python

Here are my tables. I get 0 rows return.
CREATE TABLE Artist (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Album (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
artist_id INTEGER,
title TEXT UNIQUE
);
CREATE TABLE Genre (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT
);
CREATE TABLE Track (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE,
album_id INTEGER,
genre_id INTEGER,
len INTEGER, rating INTEGER, count INTEGER
);
Here my SQL code:
SELECT Track.title, Artist.name, Album.title, Genre.name
FROM Track JOIN Genre JOIN Album JOIN Artist
ON Track.genre_id = Genre.id and Track.album_id = Album.id
WHERE Album.artist_id = Artist.id
ORDER BY Artist.name LIMIT 3
I appreciate your looking into this problem.

You code is correct sofar, but you need to fill the just created tables with records.
For example by running (untested):
INSERT INTO Artist (name) VALUES ('Artist 1'), ('Artist 2');
INSERT INTO Genre (name) VALUES ('Genre 1'), ('Genre 2');
INSERT INTO Album (title, artist_id) VALUES ('Title 1', 1);
INSERT INTO Track(title, album_id,
genre_id, len, rating, count)
VALUES ('Track 1', 1, 1, 0, 0, 0);
Also you should declare artist_id, album_id and genre_id columns as foreign keys.

Related

Attempted to autoincrement an integer value but returend null, how do I fix?

tblcustomer = """ CREATE TABLE IF NOT EXISTS Customer
(
CustomerID INT,
CustomerName TEXT,
Address TEXT,
Postcode TEXT,
EmailAddress TEXT,
primary key(CustomerID AUTOINCREMENT)
)"""
cursor.execute(tblcustomer)
connection.commit()
This is my table (I'm using sqlite3), but it returns 'null' to the table values. For my user inputs I just asked for the other 4 values and inserted them into the table, omitting 'CustomerID'. How do I fix it so it actually autoincrements?
Here's how you can modify your table to include an AUTOINCREMENT column for the CustomerID field:
CREATE TABLE IF NOT EXISTS Customer(
CustomerID INTEGER PRIMARY KEY AUTOINCREMENT,
CustomerName TEXT,
Address TEXT,
Postcode TEXT,
EmailAddress TEXT)

sql insert query with select query using pythonn and streamlit

i have an sql insert query that take values from user input and also insert the ID from another table as foreign key. for this is write the below query but it seems not working.
Status_type table
CREATE TABLE status_type (
ID int(5) NOT NULL,
status varchar(50) NOT NULL
);
info table
CREATE TABLE info (
ID int(11) NOT NULL,
name varchar(50), NULL
nickname varchar(50), NULL
mother_name varchar(50), NULL
birthdate date, NULL
status_type int <==this must be the foreign key for the status_type table
create_date date
);
for the user he has a dropdownlist that retrieve the value from the status_type table in order to select the value that he want to insert into the new record in the info table
where as the info table take int Type because i want to store the ID of the status_type and not the value
code:
query = '''
INSERT INTO info (ID,name,nickname,mother_name,birthdate,t1.status_type,created_date)
VALUES(?,?,?,?,?,?,?)
select t2.ID
from info as t1
INNER JOIN status_type as t2
ON t2.ID = t1.status_type
'''
args = (ID,name,nickname,mother_name,db,status_type,current_date)
cursor = con.cursor()
cursor.execute(query,args)
con.commit()
st.success('Record added Successfully')
the status_type field take an INT type (the ID of the value from another table ).
So when the user insert it insert the value.
What i need is to convert this value into its corresponding ID and store the ID
based on the answer of #Mostafa NZ I modified my query and it becomes like below :
query = '''
INSERT INTO info (ID,name,nickname,mother_name,birthdate,status_type,created_date)
VALUES(?,?,?,?,?,(select status_type.ID
from status_type
where status = ?),?)
'''
args = (ID,name,nickname,mother_name,db,status_type,current_date)
cursor = con.cursor()
cursor.execute(query,args)
con.commit()
st.success('Record added Successfully')
When creating a record, you can do one of these ways.
Receive as input from the user
Specify a default value for the field
INSERT INTO (...) VALUES (? ,? ,1 ,? ,?)
Use a select in the INSERT
INSERT INTO (...) VALUES (? ,? ,(SELECT TOP 1 ID FROM status_type ODER BY ID) ,? ,?)
When INSERT data, you can only enter the names of the destination table fields. t1.status_type is wrong in the following line
INSERT INTO info (ID,name,nickname,mother_name,birthdate,t1.status_type,created_date)

Update on Duplicate key with two columns to check mysql

I am trying to get my head around the 'On Duplicate Key' mysql statement. I have the following table:
id (primary key autoincr) / server id (INT) / member id (INT UNIQUE KEY) / basket (VARCHAR) / shop (VARCHAR UNIQUE KEY)
In this table each member can have two rows, one for each of the shops (shopA and shopB). I want to INSERT if there is no match for both the member id and shop. If there is a match I want it to update the basket to concat the current basket with additional information.
I am trying to use:
"INSERT INTO table_name (server_id, member_id, basket, shop) VALUES (%s, %s, %s, %s) ON DUPLICATE KEY UPDATE basket = CONCAT (basket,%s)"
Currently if there is an entry for the member for shopA when this runs with basket for shopB it adds the basket info to the shopA row instead of creating a new one.
Hope all this makes sense! Thanks in advance!
UPDATE: As requested here is the create table sql statement:
CREATE TABLE table_name ( member_id bigint(20) NOT NULL, server_id bigint(11) NOT NULL, basket varchar(10000) NOT NULL, shop varchar(30) NOT NULL, notes varchar(1000) DEFAULT NULL, PRIMARY KEY (member_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
In this table each member can have two rows, one for each of the shops
(shopA and shopB)
This means that member_id should not be the primary key of the table because it is not unique.
You need a composite primary key for the columns member_id and shop:
CREATE TABLE table_name (
member_id bigint(20) NOT NULL,
server_id bigint(11) NOT NULL,
basket varchar(10000) NOT NULL,
shop varchar(30) NOT NULL,
notes varchar(1000) DEFAULT NULL,
PRIMARY KEY (member_id, shop)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
See a simplified demo.

How do I deal with non deterministic value in SQLite3?

Below you can see the tables in my sqlite3 database:
songs
files
tags
playlists
These are the relationships between the tables:
One To One: Songs and files
Many To Many: Songs and tags, Songs and playlists
Below you can see the table queries I am using:
create_songs_table_query = """ CREATE TABLE IF NOT EXISTS songs (
song_id integer PRIMARY KEY AUTOINCREMENT,
title text NOT NULL,
artist text NOT NULL,
added_timestamp integer NOT NULL,
file_id INTEGER NULL,
FOREIGN KEY (file_id)
REFERENCES files (file_id)
ON DELETE CASCADE
); """
create_files_table_query = """ CREATE TABLE IF NOT EXISTS files (
file_id integer PRIMARY KEY AUTOINCREMENT,
filename text NULL,
size integer NULL,
song_id INTEGER NOT NULL,
FOREIGN KEY (song_id)
REFERENCES songs (song_id)
ON DELETE CASCADE
); """
create_tags_table_query = """CREATE TABLE IF NOT EXISTS tags (
tag_id integer PRIMARY KEY AUTOINCREMENT,
tag_text text NOT NULL,
tag_timestamp integer NULL,
); """
create_songs_tags_table_query = """CREATE TABLE IF NOT EXISTS songs_tags (
song_tag_id integer PRIMARY KEY AUTOINCREMENT,
song_id INTEGER NOT NULL,
tag_id INTEGER NOT NULL,
FOREIGN KEY (song_id)
REFERENCES songs (song_id)
ON DELETE CASCADE,
FOREIGN KEY (tag_id)
REFERENCES tags (tag_id)
ON DELETE CASCADE
); """
create_playlists_table_query = """CREATE TABLE IF NOT EXISTS playlists (
playlist_id integer PRIMARY KEY AUTOINCREMENT,
playlist_title text NOT NULL,
created_timestamp INTEGER NOT NULL,
updated_timestamp INTEGER NULL,
); """
create_songs_playlists__table_query = """CREATE TABLE IF NOT EXISTS songs_playlists (
song_playlist_id integer PRIMARY KEY AUTOINCREMENT,
song_id INTEGER NOT NULL,
playlist_id INTEGER NOT NULL,
FOREIGN KEY (song_id)
REFERENCES songs (song_id)
ON DELETE CASCADE,
FOREIGN KEY (playlist_id)
REFERENCES playlists (playlist_id)
ON DELETE CASCADE
); """
I am trying sucessfully to get the total songs each tag has and order by it:
SELECT tags.tag_id, tags.tag_text, COUNT(tags.tag_id) AS total, tags.included, tags.tag_timestamp
FROM tags
JOIN songs_tags ON tags.tag_id = songs_tags.tag_id
GROUP BY songs_tags.tag_id
ORDER BY total DESC
This is the query to order by tags.tag_text:
SELECT tags.tag_id, tags.tag_text, COUNT(tags.tag_id) AS total, tags.included, tags.tag_timestamp
FROM tags
JOIN songs_tags ON tags.tag_id = songs_tags.tag_id
WHERE tags.included = 1
GROUP BY songs_tags.tag_id
ORDER BY tags.tag_text
I am using Python and Pycharm. Python doesn't return any records and Pycharm shows me the following pop up in the editor window:
Nondeterministic value: column tag_text is neither aggregated, nor mentioned in GROUP BY clause
Although, if I run the query from PyCharm's database console I get the desired results.
It's a bit tricky, any ideas ?
Writer the query correctly, so the SELECT and GROUP BY columns are consistent:
SELECT t.tag_id, t.tag_text, COUNT(*) AS total, t.included, t.tag_timestamp
FROM tags t JOIN
songs_tags st
ON t.tag_id = st.tag_id
WHERE t.included = 1
GROUP BY t.tag_id, t.tag_text, t.included, t.tag_timestamp
ORDER BY t.tag_text;
This also introduced table alias so the query is easier to write and to read.

how to define multi primary keys and foreign keys in Django Model

I have two tables in Mysql DB, it looks like this:
Table1:
number int pk
type int pk
...
Table2:
number int pk fk
type int pk fk
...
I defined models in models.py like this
def Table1:
class Meta:
unique-together = ('number', 'type'),
index-together = ('number', 'type'),
primary = ('number', 'type')
number = models.IntegerField()
type = models.IntegerField()
...
When I migrate the model, The result isn't not what I want.
BEGIN;
--
-- Create model Table1
--
CREATE TABLE "multiprimary_table1" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "number" integer NOT NULL, "type" integer NOT NULL);
--
-- Alter unique_together for table1 (1 constraint(s))
--
ALTER TABLE "multiprimary_table1" RENAME TO "multiprimary_table1__old";
CREATE TABLE "multiprimary_table1" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "number" integer NOT NULL, "type" integer NOT NULL);
INSERT INTO "multiprimary_table1" ("type", "id", "number") SELECT "type", "id", "number" FROM "multiprimary_table1__old";
DROP TABLE "multiprimary_table1__old";
CREATE UNIQUE INDEX "multiprimary_table1_number_8d499fc9_uniq" ON "multiprimary_table1" ("number", "type");
--
-- Alter index_together for table1 (1 constraint(s))
--
ALTER TABLE "multiprimary_table1" RENAME TO "multiprimary_table1__old";
CREATE TABLE "multiprimary_table1" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "number" integer NOT NULL, "type" integer NOT NULL);
INSERT INTO "multiprimary_table1" ("type", "id", "number") SELECT "type", "id", "number" FROM "multiprimary_table1__old";
DROP TABLE "multiprimary_table1__old";
CREATE UNIQUE INDEX "multiprimary_table1_number_8d499fc9_uniq" ON "multiprimary_table1" ("number", "type");
CREATE INDEX "multiprimary_table1_number_8d499fc9_idx" ON "multiprimary_table1" ("number", "type");
COMMIT;
Django add ID in my table and set primary key to ID column, How can I fix it?
And I don't know how to define multi foreign key either, could somebody tell me?
Django Composite Key might be a solution for you:
https://github.com/simone/django-compositekey

Categories

Resources