这个好像很复杂的比如有个表 articleid  
uid 用户ID
title 标题id uid title
1 1 aaaa
2 1 bbbb
3 2 cccc
4 2 dddd
5 3 eeee==============================用户组 membergroupid 
groupname 用户组名称id groupname
1 普通会员
2 高级会员==============================
用户表 members
uid 用户UID
username 用户名
gid 所属用户组IDuid username gid
1 tt11 1
2 tt22 1
3 tt33 2
==============================目前想这样取 article 表的数据,  高级会员的信息排在最前面 ,其次才是普通会员的
一条SQL能实现吗? 性能怎么样呢? 比如想取 article 表的数据像这样: 5 - eeee (uid是3的会员是高级会员,排在最前面,其次的按ID降序排列, 可能还设计到按时间倒叙等等)
4 - dddd
3 - cccc
2 - bbbb 
1 - aaaa

解决方案 »

  1.   


    SELECT a.title FROM article AS a LEFT JOIN members AS b ON(b.uid=a.uid) LEFT JOIN membergroup AS c ON(c.id=b.gid) ORDER BY c.id DESC
      

  2.   

    if object_id('[article]') is not null drop table [article]
    go
    create table [article]([id] int,[uid] int,[title] varchar(4))
    insert [article]
    select 1,1,'aaaa' union all
    select 2,1,'bbbb' union all
    select 3,2,'cccc' union all
    select 4,2,'dddd' union all
    select 5,3,'eeee'
    if object_id('[embergroup]') is not null drop table [embergroup]
    go
    create table [embergroup]([id] int,[groupname] varchar(8))
    insert [embergroup]
    select 1,'普通会员' union all
    select 2,'高级会员'
    if object_id('[members]') is not null drop table [members]
    go
    create table [members]([uid] int,[username] varchar(4),[gid] int)
    insert [members]
    select 1,'tt11',1 union all
    select 2,'tt22',1 union all
    select 3,'tt33',2select a.id,a.title
    from article a
    join members b on a.uid=b.uid
    join embergroup c on c.id=b.gid
    order by 
      case when c.groupname='高级会员' then 1 when groupname='普通会员' then 2 else 3 end,
      a.id desc/**
    id          title 
    ----------- ----- 
    5           eeee
    4           dddd
    3           cccc
    2           bbbb
    1           aaaa(所影响的行数为 5 行)
    **/
      

  3.   

    SELECT a.id AS aid.a.title AS atitle 
    FROM article AS a 
    LEFT JOIN members AS m ON a.uid=m.uid 
    LEFT JOIN embergroup AS eg ON m.gid=eg.id
    ORDER a.id eg.id DESC如果附加时间排序的话,直接在ORDER BY 后面加上排序的字段即可;
    要优化的话,在3张表关联的字段建立索引,members.uid ; article.id ; membergroup.id;
      

  4.   

    select id, title from article, members where article.uid=members.uid order by members.gid, article.id desc