此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这类页面,用起来很方便。 欢迎大家一起探讨!
|