Create SQL query for the following tables - python

A database is composed of 4 tables: Table1, table2, table3 and table4.
For a given query Q. If Q = Name_1. I want to select all the fields in tables 1, 2, 3 and 4 and save them in an array using python.
create Tables:
Create Table table1 (ID1 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100));
Create table table2 (ID2 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T1 INT, Foreign Key(ID_T1) references table1(ID1));
Create table table3 (ID3 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T1 INT, Foreign Key(ID_T1) references table1(ID1));
Create table table4 (ID4 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T2 INT, Foreign Key(ID_T2) references table2(ID2));
Insert Data in tables:
insert into table1 (ID1,NAME) values ("1", "john");
insert into table2 (ID2,NAME,ID_T1) values ("1", "math","1");
insert into table3 (ID3,NAME,ID_T1) values ("1", "physics","1");
insert into table4 (ID4,NAME,ID_T2) values ("1", "friend of","1");

Here is the query:
SELECT * FROM Table1 AS t1
JOIN table3 as t3 ON t1.ID_table1 = t3.ID_table1
JOIN table2 as t2 ON t1.ID_table1 = t2.ID_table1
JOIN table4 as t4 ON t2.ID_table2 = t4.ID_table2

Related

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)

Postgres insert only new rows to the table

I have such a code,
cursor_local.execute("""SELECT "Name", "Level_Capacity", "Source_NE", "Sink_NE" FROM "table1" WHERE "Name" LIKE '%WDM%' """)
rows = cursor_local.fetchall()
psycopg2.extras.execute_batch(cursor_local, 'INSERT INTO table2("Name", "Level_Capacity", "Source_NE", "Sink_NE") VALUES (%s, %s, %s, %s)', (*rows,) )
connection_local.commit()
and I would like to insert only new records into the table2 from table1 (postgres db), only those that are not in table2.
In table2 "Id" is automatically generated and is unique (others are not unique) , when inserting I would like to check if it exists "Name", "Source_NE", "Sink_NE".
is "name" unique? maybe you can do an ON CONFLICT Name DO NOTHING
INSERT INTO table2
VALUES ,,,
ON CONFLICT 'Name' DO NOTHING;
else you could do a NOT IN (SELECT "Name" etc FROM table2) etc
INSERT INTO table2
VALUES (
SELECT * FROM table1 WHERE ('Name' etc)
NOT IN (SELECT 'Name', etc FROM table2)
)
it works:
INSERT INTO "table2" ("Name", "Level_Capacity", "Source_NE", "Sink_NE")
SELECT "Name", "Level_Capacity", "Source_NE", "Sink_NE"
FROM "table1" WHERE ("Name", "Source_NE", "Source_Port", "Sink_NE", "Sink_Port") NOT IN (SELECT "Name", "Source_NE", "Source_Port", "Sink_NE", "Sink_Port" FROM "table2");
thank you

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

Update a Joined Table with SQLAlchemy Core

I have a MySQL db with tables set up like this:
Table1 Table2
------ ------
id id, fk to Table1.id
name name
I want to update Table1 and set Table1.id = Table2.id if Table1.name = Table2.name. Or, in SQL:
UPDATE table1 t1
INNER JOIN table2 t2
ON t1.name = t2.name
SET t1.id = t2.id;
How can I accomplish an equivalent statement using the SQLAlchemy Core API?
I can call table1.join(table2, table1.c.name == table2.c.name) to create the join, but how can I update this joined table?
upd = table1.update()\
.values(id=table2.c.id)\
.where(table1.c.name == table2.c.name)
should do it, but if you really have all those foreign keys, you might get errors doing such updates.

How to create unique rows in a table?

I`m just started to learn SQLite. I use python.
The question is how to create rows in tables, so that they are uniqe by name and how to use (extract) id1 and id2 to insert them into a separate table.
import sqlite3
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table1(
id1 integer primary key autoincrement, name)''')
c.execute('''CREATE TABLE IF NOT EXISTS table2(
id2 integer primary key autoincrement, name)''')
c.execute('CREATE TABLE IF NOT EXISTS t1_t2(id1, id2)') # many-to-many
conn.commit()
conn.close()
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('INSERT INTO table1 VALUES (null, "Sue Monk Kidd")')
c.execute('INSERT INTO table2 VALUES (null, "The Invention of Wings")')
#c.execute('INSERT INTO t1_t2 VALUES (id1, id2)')
c.execute('INSERT INTO table1 VALUES (null, "Colleen Hoover")')
c.execute('INSERT INTO table2 VALUES (null, "Maybe Someday")')
#c.execute('INSERT INTO t1_t2 VALUES (id1, id2)')
Thanks.
I think you have some problems with the table creation. I doubt that it worked, because the name columns don't have a type. They should probably be varchar of some length. The JOIN table definition isn't right, either.
CREATE TABLE IF NOT EXISTS table1 (
id1 integer primary key autoincrement,
name varchar(80)
);
CREATE TABLE IF NOT EXISTS table2 (
id2 integer primary key autoincrement,
name varchar(80)
);
CREATE TABLE IF NOT EXISTS t1_t2 (
id1 integer,
id2 integer,
primary key(id1, id2),
foreign key(id1) references table1(id1),
foreign key(id2) references table2(id2)
);
I would not create the tables in code. Script them, execute in the SQLite admin, and have the tables ready to go when your Python app runs.
I would think much harder about your table names if these are more than examples.
I found the problem of unique names on unique column problem.
Actually, I should change INSERT to INSERT OR IGNORE
import sqlite3
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table1(
id1 integer primary key autoincrement, name TEXT unique)''')
c.execute('''CREATE TABLE IF NOT EXISTS table2(
id2 integer primary key autoincrement, name TEXT unique)''')
c.execute('CREATE TABLE IF NOT EXISTS t1_t2(id1, id2)') # many-to-many
conn.commit()
conn.close()
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('INSERT OR IGNORE INTO table1 VALUES (null, "Sue Monk Kidd")')
c.execute('INSERT OR IGNORE INTO table2 VALUES (null, "The Invention of Wings")')

Categories

Resources