iT邦幫忙

0

sql server 複數欄位條件篩選

想請教一下各位高人
若我想在SQL下條件於複數欄位(約7~80個欄位)只要一個欄位有值就撈出來,請問有沒有比較不吃資源的作法?
我目前是下OR,一欄一欄key一欄一欄比對,資料筆數約十幾萬.....所以很刺激@@
煩請各方高人指點迷津,感恩感謝~

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
一級屠豬士
iT邦新手 2 級 ‧ 2017-11-08 21:39:07
最佳解答
create table ithelp170811 (
  id int not null
, c1 char(1)
, c2 int
, c3 int
, c4 int
, c5 char(1)
);

insert into ithelp170811 values
(1, 'a', null, null, null, null),
(2, null, null, null, null, null),
(3, null, 4, null, null, null),
(4, null, null, 5, null, null),
(5, 'b', 2, 3, 4, null),
(6, null, null, null, 7, null),
(7, null, null, null, null, 'c');

-- use the ANSI coalesce function for same type columns

select *
  from ithelp170811
 where coalesce(c1, c5) is not null
    or coalesce(c2, c3, c4) is not null;
     
 id |   c1   |   c2   |   c3   |   c4   |   c5   
----+--------+--------+--------+--------+--------
  1 | a      | [null] | [null] | [null] | [null]
  3 | [null] |      4 | [null] | [null] | [null]
  4 | [null] | [null] |      5 | [null] | [null]
  5 | b      |      2 |      3 |      4 | [null]
  6 | [null] | [null] | [null] |      7 | [null]
  7 | [null] | [null] | [null] | [null] | c
(6 筆資料列)

我要發表回答

立即登入回答