Home > Software engineering >  How do I fetch two column values in mysql?
How do I fetch two column values in mysql?

Time:02-17

I have a column with different stored data (user, street, country).

What I am trying to do is the following:

await cur.execute("SELECT street, country FROM dbname WHERE user=%s AND user=%s", (user1, user2,))
result = await cur.fetchone()
print(result)

So I am trying to print the two users and their street and country. The output is always empty or gives me an error. Is this even possible in that way? I have looked through many examples but have not found anything on my matter.

I also tried to use fetchmany() and fetchall() but still no result. Maybe I am overcomplicating some things here.

For reference, I have looked at the following pages:

  1. how to compare two column values in mysql stored procedure
  2. Mysql: Selecting values between two columns
  3. https://www.tutorialspoint.com/select-a-specific-value-between-two-column-values-in-mysql

A working solution could be:

await cur.execute("SELECT street, country FROM dbname WHERE user=%s", (user1,))
result = await cur.fetchone()
print(result)

await cur.execute("SELECT street, country FROM dbname WHERE user=%s", (user2,))
result1 = await cur.fetchone()
print(result1)

However, I have to execute some code twice. Is this already bad practice or doable in some cases/not avoidable at some point?

CodePudding user response:

You should update the SQL statement to SELECT street, country FROM dbname WHERE user=%s OR user=%s

The output is empty because a single row user cannot be both user1 and user2

  • Related