sql语句

23 Jun 2013, by

基本命令

create table 表名
(
  Id int ,   
  Name varchar(50),  --varchar可变长度   
  sex char(2)   --char固定长度   
)   

高级命令

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
JOIN: 如果表中有至少一个匹配,则返回行
LEFT JOIN: 即使右表中没有匹配,也从左表返回所有的行
RIGHT JOIN: 即使左表中没有匹配,也从右表返回所有的行
FULL JOIN: 只要其中一个表中存在匹配,就返回行

子查询, 别名, 临时表

def self.get_clubs_photo_walls
    PhotoWall.select("photo_walls.*, (case when tmp_club_users.members is null then 0 else tmp_club_users.members end) members")
    .joins("inner join clubs on photo_walls.photo_wall_able_id = clubs.id and photo_walls.photo_wall_able_type='Club' ")
    .joins("left join (select count(*) members,club_id from club_users group by club_id ) tmp_club_users on tmp_club_users.club_id = photo_walls.photo_wall_able_id")
    .order("photo_walls.pos asc, members desc")
  end