简体   繁体   中英

SQL WHERE command with multiple operators

We have a database with a column labeled "pr_label" and "pr_quantity". When we query our information the items labeled as "C1" and "C2" display. Below is the code we used in our SQL command

'pr_label' IN ('C1', 'C2')

but now we want to add an extra rule where we want to display all "C1" items and only "C2" items that have a value greater than zero in "pr_quantity". So if we applied these rules the below table will only display info on 900, 901, 902 and 903. 904 and 905 would not display because 'pr_quantity' == 0.

 =====================================
 pr_id     | pr_label  | pr_quantity |
 =====================================
 900       | C1        | 4           |
 901       | C1        | 4           |
 902       | C1        | 4           |
 903       | C2        | 4           |
 904       | C2        | 0           |
 905       | C2        | 0           |
 =====================================

I am trying the code below which works but it applies to both "C1" and "C2".

`pr_quantity ` > 0

You should be able to simply say:

WHERE (pr_label = 'C1')
    OR (pr_label = 'C2' AND pr_quantity > 0)

To answer this

we want to display all "C1" items and only "C2" items that have a value greater than zero in "pr_quantity"

the following query would be handy (I'm going to call this as product table)

SELECT 
    *
FROM PRODUCT
WHERE 
pr_label = 'C1' OR (pr_label = 'C2' AND pr_quantity > 0)

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