简体   繁体   中英

Showing particular MySQL table fields for a single row

I have a MySQL table with 8 fields/columns. Of these, 5 columns have either 0 or 1 as values. I would like to show only those fields whose value is 1 for a particular ro .
The obvious method is to run a query like this:

SELECT * FROM table WHERE  field1=1 OR field2=1 OR field3=1 OR field4=1 OR field5=1 ;

This will yield a resultset containing 8 fields/columns where the conditions are satisfied.

But what I want to try is to run a query which gives a result-set containing only that fields which has 1 as value.

Is it possible?
If possible, how can I do this?

Unfortunately, I don't think this is possible. If you think about it when reading the resultset you'll have to for example do :

$row[0]

Which will vary from row to row with what you're trying to do. The result of $row[0] will always be 1 but the column selected will differ from row to row, which is pretty confusing IMO.

A solution would be to change the design of the table and set:

visibleField1, visibleField2, visibleField3, visibleField4, visibleField5

and fill the column with the name of the field you want to show.

or name the field visibleFields and fill it with "field1,field2,field5" when you want to show those three

There's probably other ways to do this design change.

You could try it like this:

SELECT id, 
CASE
WHEN field1 = 1 THEN 'badge_name'
WHEN field2 = 1 THEN 'other_badge_name'
...
END AS badge
FROM your_table

You can see an example at the link below that uses a couple stack overflow badges:

http://sqlfiddle.com/#!9/189061/1

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