简体   繁体   中英

Select, or not select a field based on a value in the next field

From a table like this (this is just for here):

p_add  | p_add_s | p_phone | p_phone_s | p_user_id //0 = show 1= Hide
Address| 0       | 12345   | 1         | 1
Addr   | 0       | 12345   | 1         | 2

How can I do a select like:

 select p_add (if p_add_s = 0), p_phone (if p_phone_s=0) from table where p_user_id=1
or
    select p_add, p_phone from table where p_user_id=1 (if p_add_s = 0) and (if p_phone_s = 0)

These are incorrect. I included them just so u can get an idea.

Actually I only need data if the value with _s is 0.

Can this be done using sql or it'll have to achieved using php?

I think you are looking for the mysql IF syntax:

select if(p_add_s=0, p_add, 'Address Private'),  if(p_phone_s=0, p_phone, 'Phone Private') from myTable

If the condition is met, it returns the middle section, otherwise, the last one.

Alternately, based on your second query:

select p_add, p_phone from table where p_user_id=1 and p_add_s = 0 and p_phone_s = 0

Note that this will not return rows where all the conditions within the where clause are not met, so the if statement might work better.

select p_add, p_phone from table where p_user_id=1 and p_add_s=0 and p_phone_s=0
SELECT p_add FROM yourtable
WHERE p_user_id = 1
AND p_add_s = 0
AND p_phone_s = 0

Don't forget to use PDO .

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