bianbian coding life

便便代码人生: 关注技术, 翻译文档, 偶尔动动手

[原]PostgreSQL complex query(PostgreSQL的复杂查询)

Posted by bianbian on 2006-09-19 14:27

本文Tags: ,

试了一会儿,先记下来。省得以后忘掉。

Well, the tables are: (tag的表情况,usertags表记录了每个用户的tag(一行记录一个tag),usersites表记录了每个url对应的多个tags,urltags表记录了一个usersiteid对应多个usertagid(反过来也是一个usertagid对应多个usersiteid))

  1. usertags                  usersites                       urltags
  2. =======================================================================
  3. 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 语句如下:

  1. SELECT count(t.usersiteid) AS count, t.usertagid, n.tagname
  2.   FROM urltags t, usertags n
  3.     WHERE t.usertagid=n.id
  4.     AND usertagid in ( select DISTINCT on (usertagid) usertagid from urltags )
  5.   group by t.usertagid,n.tagname
  6.   order by count DESC

中间的子查询“select DISTINCT on (usertagid) usertagid from urltags ”查询出所有对照表里的usertagid,其中DISTINCT on(usertagid)表示只查询出usertagid字段不重复的记录(即多个相同的usertagid值的话只取一个)。DISTINCT的写法可能只是postgreSQL的特殊函数,不过相信其他数据库应该也有不同写法的支持。
执行结果截图,应该是对的吧。。。。呵呵:
Postgresql_query

标签: ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

(required)