Skip to content
Advertisement

Can’t Insert into seperate column while using two select statements

import mysql.connector
mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database="resume")
cursor = mydb.cursor()
a = "SELECT ENTITY FROM annotate1 WHERE LABEL = 'NAME' GROUP BY PAGE"
cursor.execute(a)
records = cursor.fetchall()
for i in records:
    name = i[0]
    query = "INSERT INTO sorting_report(NAME) VALUES (%s)"
    parameters = (str(name),)
    cursor.execute(query, parameters)
    mydb.commit()
print("Name inserted")

b = "SELECT ENTITY FROM annotate1 WHERE LABEL = 'ADDRESS' GROUP BY PAGE"
cursor1 = mydb.cursor()
cursor1.execute(b)
records1 = cursor1.fetchall()
for i in records:
    address = i[0]
    query = "INSERT INTO sorting_report(ADDRESS) VALUES (%s)"
    parameters = (str(address),)
    cursor.execute(query, parameters)
    mydb.commit()
print("Address inserted")

TABLE:

NAME : Jance C hiatt, Sam, Brook, Newyork, London ADDRESS : NULL,NULL,NULL,NULL

NewYork and London should be address column but it is showing on Name itself

Here address is not coming at the separate column of database. Kindly tell me what issue I am facing

Advertisement

Answer

Each insert statement creates new rows, so you cannot expect your queries to automagically align related values on the same row.

I suspect that you have an EAV model that looks like that:

page     label   entity
+-------+-------+--------
page1    NAME    foo
page1    ADDRESS bar

And you want to pivot it in the target table like so:

page    name    address
+------+-------+--------
page1   foo     bar

You can do this in a single statement, using conditional aggregation:

insert into sorting_report(page, name, address)
select page,
    max(case when label = 'NAME'    then entity end),
    max(case when label = 'ADDRESS' then entity end)
from annotate1 
group by page
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement