SQLite Copying data to second table from first table - python

I have two tables created from below query in SQLite:
CREATE TABLE people (
id integer unique primary key,
first_name text,
middle_name text,
last_name text,
email text,
phone text
);
CREATE TABLE companies (
id integer unique primary key,
name text,
url text,
contact integer,
FOREIGN KEY(contact) REFERENCES people(id)
);
I have all the data available in the first table, but I want to popup id in second table same as id in the first table.name in the companies table is concatenated string of first_name text,middle_name,last_name in people table.
I want something like "UPDATE companies SET contact = (SELECT people.id FROM people WHERE companies.name = people.first_name || "," || "people.second_name"; it will be great if I can show the string in people table is the subset of string in companies table
I am a beginner in python and SQlite both.

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)

How can I list the data of foreign keys linked to the id of the table?

What I want to do is create 4 interconnected progressive category classes.I don't know if the method I did is correct. Unfortunately I have been reading the document for days. but I haven't made much progress
Over the 'company' class how can I query all data belonging to the 'DepartmentalUnit' class?
create_table_company= '''CREATE TABLE company(
ID SERIAL PRIMARY KEY ,
NAME VARCHAR NOT NULL ,
); '''
create_table_department = '''CREATE TABLE department (
ID SERIAL PRIMARY KEY ,
NAME VARCHAR NOT NULL ,
company_id BIGINT,
FOREIGN KEY(company_id) REFERENCES COMPANY(id)); '''
create_table_department_unit = '''CREATE TABLE department_unit(
ID SERIAL PRIMARY KEY ,
NAME VARCHAR NOT NULL ,
department_id BIGINT,
FOREIGN KEY(department_id) REFERENCES DEPARTMENT(id));
create_table_department_unit_categroy = '''CREATE TABLE department_unit_category(
ID SERIAL PRIMARY KEY ,
NAME VARCHAR NOT NULL ,
department_unit_id BIGINT,
FOREIGN KEY(department_unit_id) REFERENCES DEPARTMENT_UNİT(id));
Something like this:
SELECT
c.id, c.name, du.*
FROM
company AS c
JOIN
department AS d
ON
c.id = d.company_id
JOIN
department_unit AS du
ON
du.department_id = d.id
;
UPDATE
The above query works to get the department_unit information by connecting the tables by their common fields. In this case the company table finds the department information for each company by using the company_id field in department that links back to a company. Once the departments for a company are found the department units for each department is found by using the department_id field in department_unit to link back to the department table. The end result is a chain that connects a company to its department units.

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.

(Python, sqlite3) Building relational database?

I am trying to create a relational database in python with sqlite3. I am a little fussy on how to connect the tables in the database so that one entity connects to another via the second table. I want to be able to make a search on a persons name via a webpage and then find the parents related to that person. Im not sure if I need two tables or three.
This is how my code looks like right now:
class Database:
'''Initiates the database.'''
def __init__(self):
self.db = sqlite3.connect('family2.db')
def createTable(self):
r = self.db.execute('''
CREATE TABLE IF NOT EXISTS family2 (
id INTEGER PRIMARY KEY ASC AUTOINCREMENT,
fname TEXT,
sname TEXT,
birthdate TEXT,
deathdate TEXT,
mother TEXT,
father TEXT
)''')
self.db.commit()
g = self.db.execute('''CREATE TABLE IF NOT EXISTS parents(
id INTEGER PRIMARY KEY ASC AUTOINCREMENT,
mother TEXT,
father TEXT)''')
self.db.commit()
b = self.db.execute('''CREATE TABLE IF NOT EXISTS relations(
id INTEGER PRIMARY KEY ASC AUTOINCREMENT,
family2,
parents TEXT
)''')
self.db.commit()
Thanks in advance!
You don't need multiple tables; you can store the IDs of the parents in the table itself:
CREATE TABLE persons(
id INTEGER PRIMARY KEY,
name TEXT,
mother_id INT,
father_id INT
);
You can then find the mother of a person that is identified by its name with a query like this:
SELECT *
FROM persons
WHERE id = (SELECT mother_id
FROM persons
WHERE name = '...')

Categories

Resources