简体   繁体   中英

Select the result where multiple columns

I need to select the result with check the multiple columns.

 SELECT * FROM atricle WHERE  
    a.article_free_1 = 1 AND  
    a.article_free_2 = 1 AND 
    a.article_free_3 = 1 AND 
    a.article_free_4 = 1 AND 
    a.article_free_5 = 1 AND 
    a.article_free_6 = 1 AND 
    a.article_free_7 = 1 AND 
    a.article_free_8 = 1 AND 
    a.article_free_9 = 1 AND 
    a.article_free_10 = 1;

Here I want to simplify the query.Its going very long and I need to add 40+ columns in my query.

How to simplify my query?

If you are using this query very frequently then its better to create a calculated/computed column in the table. This will be like this:

(CASE WHEN article_free_1 = 1 
       AND article_free_2 = 1 AND ....THEN 1 ELSE 0 END)

you can replace the query with :

SELECT * FROM atricle WHERE <computedColumn> = 1

it should simplify the query and give you optimized result eachtime you execute it.

I can't simply comment yet so I'll post as an answer. Your query is as optimal as it can get. A calculated field will just add overhead, getting in the way of the query optimizer trying to evaluate. Whatever you do, DON'T loop in sql, it was a horrendous addition way back trying to make people like SQL. Stick to standard queries. What you got is good.

-Edit I jus read what Jeemusu wrote. spot on.

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