[原]PostgreSQL complex query(PostgreSQL的复杂查询)
Posted by bianbian on 2006-09-19 14:27
本文Tags: PostgreSQL, 数据库
试了一会儿,先记下来。省得以后忘掉。
Well, the tables are: (tag的表情况,usertags表记录了每个用户的tag(一行记录一个tag),usersites表记录了每个url对应的多个tags,urltags表记录了一个usersiteid对应多个usertagid(反过来也是一个usertagid对应多个usersiteid))
- usertags usersites urltags
- =======================================================================
- id tagname userid id url title userid tags id usersiteid usertagid
now we need to get all tagnames, tagid, and used times of a tag, sorted by used times, how to do it? (现在我们需要一次查询得到所有的tagname、每个tag对应的tagid和使用次数并按使用次数排序)
SQL 语句如下:
- SELECT count(t.usersiteid) AS count, t.usertagid, n.tagname
- FROM urltags t, usertags n
- WHERE t.usertagid=n.id
- AND usertagid in ( select DISTINCT on (usertagid) usertagid from urltags )
- group by t.usertagid,n.tagname
- order by count DESC
中间的子查询“select DISTINCT on (usertagid) usertagid from urltags ”查询出所有对照表里的usertagid,其中DISTINCT on(usertagid)表示只查询出usertagid字段不重复的记录(即多个相同的usertagid值的话只取一个)。DISTINCT的写法可能只是postgreSQL的特殊函数,不过相信其他数据库应该也有不同写法的支持。
执行结果截图,应该是对的吧。。。。呵呵:
遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道