SQL 多欄位模糊匹配關鍵字查詢
http://www.west.cn/info/html/wangluobiancheng/Mssql/20080505/72303.html
我們開發資料庫應用時,常常需要用到模糊查詢。如果同一個條件需要匹配很多欄位怎麼辦呢?通常,程式設計師會每個欄位都在SQL中“field like'%cond%'”一次。這樣,SQL語句會長得驚人,碰上覆雜一點的,甚至SQL語句會因為超長而被資料庫拒絕執行。其實,這個問題只要動動腦筋就很容易解決:首先,將要匹配相同條件的欄位連起來(field1+field2+...)成一個長字串;然後再 Like “%cond%”就可以了。不過這種方法有個問題,就是得權衡多表連線造成的效率降低。一般來說,單表內欄位肯定應該連線後再統一like判斷;表間欄位,則需要先過濾後,再實行這個策略。採取這個策略,不僅可以縮短SQL,而且能夠有效地提高SQL的執行效率。
例:
以下為引用的內容: QUOTE: create table orders ( id int not null auto_increment, name varchar(100) not null, email varchar(255) not null, address text not null, pay_type char(10) not null, shipped_at datetime null, primary key (id) ); |
裡面有資料
1 aaa [email protected] beijing cc 2006-10-11 16:17:26
現在想要查找出email為aaa開頭的,address為bei開頭的記錄
那麼一般我們會構建如下SQL
select * from orders o where o.email like "aaa%" and o.address like "bei%"
其實我們可以使用如下SQL來縮短SQL語句(也就是連線欄位一起進行like操作)
SELECT * FROM orders o where concat(o.email,o.address) like "like%df%"
多表的情況意思是說where子句先寫連線子句進行過濾再寫連線like語句進行檢索
比如:
SELECT * FROM line_items l,orders o where l.order_id=o.id and concat(l.quantity,o.email) like "3%like%"
其中line_items表
以下為引用的內容: create table line_items ( id int not null auto_increment, product_id int not null, order_id int not null, quantity int not null default 0, unit_price decimal(10,2) not null, constraint fk_items_product foreign key (product_id) references products(id), constraint fk_items_order foreign key (order_id) references orders(id), primary key (id) ); |