简体   繁体   中英

Inverse SQL: SELECT column_name WHERE value

Let's assume we have table logins:

id| name  | lastname
---------------------
1 | mark  | johnson
2 | jack  | sparrow
3 | bruno | mark

We all know, that we can query SQL similiar to: SELECT name FROM login WHERE id = 1; and get in return mark .

I am looking for query like:

SELECT column_name FROM logins WHERE value = 'mark';

which will result in name, lastname or even

SELECT column_name FROM logins WHERE value = 'mark' AND id = 1;

which will result in name .

EDIT: The question is more complex than simple answers given. Real problem is how to select column name from 100+ columns, when we know expected value. For example we know that somewhere in table there is value 17,58 , but we want to find column name.

Getting the column name directly is not possible however using the case statement you can construct the query to return the column name for a matched value something as

select
id,
case 
 when name = 'mark' then 'name' 
 when lastname = 'mark' then 'lastname'
 else 'Nothing'
end as column_name 
from logins

DEMO

In PostgreSQL you can use the hstore extension for this (I don't think there is anything remotely similar available in MySQL):

with login_data as (
  select id, 
         skeys(hstore(l)) as column_name,
         svals(hstore(l)) as column_value
  from logins as l
  where avals(hstore(l)) @> array['mark']
) 
select id, column_name
from login_data
where column_value = 'mark'
;

SQLFiddle example: http://sqlfiddle.com/#!15/115d5/1

But the performance will most probably be quite horrible.

如果您想在(名称)或(姓氏)ID中获得名称,则认为这将对您有所帮助

SELECT column_name FROM logins WHERE ( name  = 'mark' Or lastname = 'mark') AND id = 1;

如果您不知道用户ID,则类似以下内容:

SELECT DISTINCT name FROM logins WHERE name = 'mark';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM