简体   繁体   中英

mysql query for selecting data in multiple columns

I have table with 10 columns and I want to check input value in where clause of the MySQL query.

I want to do something like this. But, when I use this query I am getting an error.

for example :

SELECT * FROM user_data 
where poll_title='$poll_title' 
and '$voter' IN (user_vote_1,user_vote_2,user_vote_3...user_vote_10) 
order by idpoll ASC

user_vote_1 to 10 (value is null'ed in the database) and I want to retrieve only that rows from a column which have $voter value.

I think you need this comparison (Not Sure OfCourse) :-

SELECT * FROM user_data 
where poll_title = "$poll_title"
  and (user_vote_1 = "$voter"
  OR user_vote_2 = "$voter" 
  OR user_vote_3 = "$voter" 
  OR user_vote_4 = "$voter"......OR user_vote_10 = "$voter")
order by idpoll ASC

If I've understood what you want to do - return only the column with the value - then would coalesce do the job? This assumes that the value in user_vote_n will either match the value you're looking for or be null, since coalesce returns the first non-null argument.

(untested)

select coalesce(user_vote_1, user_vote_2, user_vote_3, ) as UserVote from user_data where coalesce(user_vote_1, user_vote_2, user_vote_3, ) = '$voter';

That aside, this looks like a structure that could do with normalising - a single 'user_vote' column and a single 'user_vote_number' column.

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