I’m using pyodbc and postgres.
Can I alias multiple columns?
Here’s the description of my problem:
Data structure:
data
id | c1 | c2
-------------
1 | 11 | 12
2 | 21 | 22
Notation: c is for column
dictionary
id | key | value
----------------
1 | k1 | v11
1 | k2 | v12
2 | k1 | v21
2 | k2 | v22
Notation: k is for key, v is for value
You can think of k1 and k2 as two more columns. The data structure is this way because it’s constantly changing. I didn’t design it, I just have to go with it.
I can’t figure out an sql query to give me something like the following (most importantly, for some row, I can access k1 and k2 columns by some name):
data
id | c1 | c2 | k1 | k2
-------------------------
1 | 11 | 12 | v11 | v12
2 | 21 | 22 | v21 | v22
The problem I keep running into is if I alias the tables, then the sql result will contain two “key” columns from the dictionary table, meaning I can’t control which column I access of the two, but if I alias the rows, then I can’t control which tables are being referenced inside the sql statement.
The fix I’m thinking is to alias two columns:
SELECT * FROM data
FULL JOIN dictionary AS a1,a2,a3
ON data.id = a1
FULL JOIN dictionary AS a4,a5,a6
ON data.id = a4
WHERE a2 = k1 and a5 = k2
Notation: a is for alias
The result of this would theoretically look like
data
id | c1 | c2 | a3 | a6
-------------------------
1 | 11 | 12 | v11 | v12
2 | 21 | 22 | v21 | v22
Note all a’s would technically be here, but 3 and 6 are the ones I’m interested in
You can alias the entire table, for example
dictionary as d1. Then refer to the column names in that table asd1.col1. For example: