查询多列中的一个值

时间:2014-03-07 13:17:22

标签: php sql postgresql psql

我正在使用PHP和PostgreSQL并运行以下查询:

$mobile = 1234;
SELECT pri_mobile, pri_mobile2, sec_mobile, sec_mobile2 
FROM contacts 
WHERE pri_mobile=$mobile 
    OR pri_mobile2=$mobile 
    OR sec_mobile=$mobile 
    OR sec_mobile2=$mobile

我想知道找到$mobile的字段。

我能想到的一种方法是循环,如果在任何字段中找到,那么就打破循环。只是想知道是否有更简单的方法来做到这一点?

由于

2 个答案:

答案 0 :(得分:0)

我想到了这个解决方案:

select source from
(
select pri_mobile as value, 'pri_mobile' as source FROM contacts
union
select pri_mobile2 as value, 'pri_mobile2' as source FROM contacts
union
select sec_mobile as value, 'sec_mobile' as source FROM contacts
union
select sec_mobile2 as value, 'sec_mobile2' as source FROM contacts
)
where value = $mobile

我不会把它称为漂亮但是=)

答案 1 :(得分:0)

$mobile = 1234;

SELECT CASE 
  WHEN pri_mobile = $mobile then 'pri_mobile' 
  WHEN pri_mobile2 = $mobile then 'pri_mobile2' 
  WHEN sec_mobile = $mobile then 'sec_mobile'
  WHEN sec_mobile2 = $mobile then 'sec_mobile2'
END as my_column_name

FROM contacts 

WHERE pri_mobile=$mobile 
    OR pri_mobile2=$mobile 
    OR sec_mobile=$mobile 
    OR sec_mobile2=$mobile