查詢兩個表中欄位個數不同,名稱不同的SQL語句

來源:互聯網
上載者:User
語句 此sql語句能對兩個不同表不同結構不同欄位進行查詢,並且能分出哪個記錄是屬於哪個表中的

有兩個表
table1結構如下
id title content


table2結構如下
id content bigclass smallclass



sql="select id, title, content,'' as bigclass,'' as smallclass, 'tbl1' as tbl from table1 where title like '%"&keyword&"%' or content like '%"&keyword&"%' union select id, '' as title, content,bigclass,smallclass, 'tbl2' as tbl from table2 where content like '%"&keyword&"%' order by id desc"

這條語句即可實現查詢。
以asp為例,則通過
set rs=conn.execute(sql)
while not rs.eof
……
……
response.write rs("tbl")'此值就是判斷資料是哪個表的
……
……
rs.movenextwend

分析以上sql語句,其實也就是通過as把兩個表中的欄位名統一,欄位數不夠的用('')括弧內的,即空串代替,當然如果你願意也可以用非空串代替如('this is bigclass belong to table2'),這樣也可便於區分是哪個表中的資料。此sql語句中巧妙地運用了'tbl1' as tbl這條來判斷語句是屬於哪個表的,以便對資料進行處理,特別是對於站內搜尋,搜尋不同表時在一個頁面顯示結果,根據不同的表把不同的id值傳入不同表所對應的顯示頁面,有的要用readnews.asp有的要用other.asp這類頁面,用起來很方便。
歡迎大家一起探討!



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.