how to return value from key/value dict using SQL from a table that stores keys?

时间:2018-12-19 11:31:53

标签: mysql sql postgresql

I have a table where I store ids of some resources. I want to make sql return values for a keyvalue dictionary without post processing and without a JOIN.

This would be possible using a JOIN. Is there other way to do it, as I only have a few elements in the key/value array.

Programming language is not important. I'm only looking for the SQL that would be able to do it. Postgresql or Mysql.

For the table:

|objectId|attribute1|attribute2|
|45      | x        | y        |
|67      | x1       | y2       |
...

and I have a dict (object/dict/key value array):

{ 45: "My title", 67: "Other title" }

And sql result should contain titles instead of values for objectId.

select objectId, attribute1 
from table

would return:

My title | x
Other title | x1

1 个答案:

答案 0 :(得分:1)

Are you looking for a case expression?

select (case when objectId = 45 then 'My title'
             when objectId = 67 then 'Other title'
        end),
       attribute1
from t;