-3

I wrote the code in MY SQL

SELECT *
FROM employees w,
     employees m
WHERE w.manager_id = m.emp_id
  AND w.salary> m.salary;

My question is how will I execute the same question using Python?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
vs26
  • 11
  • 2
  • 2
    I would question why, you would do this. SQL is best suited for answering questions like this. SQL is optimized for set oriented queries, like the one you have asked now – George Joseph Nov 03 '20 at 03:53
  • Does this answer your question? [How do I connect to a MySQL Database in Python?](https://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python) – Pranav Hosangadi Nov 03 '20 at 03:53

1 Answers1

0
import mysql.connector as ms
mycon = ms.connect(host = "<localhostmostly>", user = "<yourusernameinSQL>", passwd = "<yourpwd>", database = "<yourdbname>")
mycursor = mycon.cursor()

query = '''SELECT *
FROM employees w,
     employees m
WHERE w.manager_id = m.emp_id
  AND w.salary> m.salary;'''

mycursor.execute(query)

This is the solution to your problem. If you want to print the results in Python, then write this line after the previously written code.

myresult = mycursor.fetchall()
print(myresult)

Hope this solved your problem! If you are writing the query in Python in a single line, do not use triple quotes (you will mostly be knowing that, but I thought I should say).

Arya
  • 54
  • 8
  • thanks, Arya, but actually my question { 'emp_id':1.'emp_name':X,Sal=1000,Manager_name=y, manager_id=5}......How will iterate over these rows to find a list of employees whose sal is greater than their manager? – vs26 Nov 03 '20 at 04:16
  • Are you having the rows as a dictionary? And if possible can you attack your table so that I can tell you a better solution? – Arya Nov 03 '20 at 04:32
  • Your table as in the way you are storing it in Python.. Like a dictionary, a list or however you are storing the values – Arya Nov 03 '20 at 04:33
  • Instead of creating a data frame, I'm showing a dictionary with a key-value pair for the employee table – vs26 Nov 03 '20 at 04:58