New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[每日见闻-2017-08-02]sql整理 #6

xiaohesong opened this Issue Aug 2, 2017 · 1 comment


None yet
1 participant
Copy link

xiaohesong commented Aug 2, 2017


  • Left join
select count(distinct store_name) from scores left join stores on scores.scoreable_id = and scores.scoreable_type = 'Store' where store.status = 0 and scores.user_type=0;
# 这个是查询 所有带有评分的门店,并且门店是营业状态(0)和评分的类型是用户评分(0)
  • Right join
    left join差不多.不过这个是以右表全表为基础进行处理.

  • inner join
    rubyjoins.sql查询中也可以直接使用join,就是inner join

# => "SELECT `users`.* FROM `users` INNER JOIN `users_roles` ON `users_roles`.`user_id` = `users`.`id` INNER JOIN `roles` ON `roles`.`id` = `users_roles`.`role_id`"

Inner join 是左右表等价的.

  • includes
A.includes(:bs).where(bs: {name: '#'}).count
# =>
# SELECT COUNT(DISTINCT `bs`.`id`) FROM `as` LEFT OUTER JOIN `bs` ON `bs`.`a_id` = `as`.`id` WHERE `bs`.`name` = '#'

从上面可以发现,left joinincludesleft outer join很像.其实left joinleft outer join类似于joininner join类似的.此处查看


  • sum
SUM(CASE WHEN num > 0 THEN 1 else 0 END) AS available_times
  • round
# 123.654 取小数后两位
    返回拼接的字符串. GROUP_CONCAT与group by使用,效果更佳.

This comment has been minimized.

Copy link
Owner Author

xiaohesong commented Aug 28, 2017

  • boolean转为汉字显示
select name, if(status>0,'激活','锁定') AS '操作状态' from users where status is not null;

@xiaohesong xiaohesong added the TIL label Feb 9, 2018

@xiaohesong xiaohesong closed this Feb 11, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment