美文网首页
MySQL查询技巧

MySQL查询技巧

作者: alpha18 | 来源:发表于2019-03-10 21:06 被阅读0次

1.行转列

SELECT user_name,
    MAX(CASE course WHEN "math" THEN score ELSE 0 END) AS "math", 
    MAX(CASE course WHEN "English" THEN score ELSE 0 END) AS "English", 
    MAX(CASE course WHEN "Chinese" THEN score ELSE 0 END) AS "Chinese"
    FROM tb GROUP BY user_name

2.列转行

select user_name, 'math' course, math_score as score from tb
    union select user_name, 'English' course English_score as score from tb
    union select user_name, 'Chinese' course Chinese_score as score from tb
    order by user_name, course;

3.在子查询中实现多列过滤

  • 单列:
select * from person where name in (select name from job)
  • 多列:
select * from person where(name, sex) in (select name, sex from job)

4.同一属性的多值过滤

select a.no, a.name, b.subject, b.score, c.subject, c.score from student a 
    join stscore b on a.no = b.stno 
    join stscore c on b.stno = c.stno
    and b.subject='math' and b.score>85 and c.subject ='English' and c.score>85;
  • 使用关联进行查询
select a.name, b.subject, b.score, c.subject, c.score, d.subject, d.score from student a
  left join stscore b on a.no = b.stno and b.subject = 'math' and b.score > 85 
  left join stscore c on a.no = c.stno and c.subject = 'English' and c.score > 85
  left join stscore d on a.no = d.stno and d.subject = 'Chinese' and d.score > 85
  where(case when b.subject is not null then 1 else 0 end) +
       (case when c.subject is not null then 1 else 0 end) +
       (case when d.subject is not null then 1 else 0 end) >= 2
  • 使用Group by实现查询
select a.name from student a join stscore b on a.id = b.stno where
    b.subject in ('math', 'English', 'chinese') and b.score > 0 
    group by a.name having count(*) >= 2

相关文章

  • MySQL查询技巧

    1.行转列 2.列转行 3.在子查询中实现多列过滤 单列: 多列: 4.同一属性的多值过滤 使用关联进行查询 使用...

  • MySQL索引知多少

    mysql索引 总结关于mysql的索引,查询优化,SQL技巧等 1 索引类型 B-Tree索引 Hash索引 ...

  • 10分钟掌握数据类型、索引、查询的MySQL优化技巧

    10分钟掌握数据类型、索引、查询的MySQL优化技巧? 不存在的! 本文的内容是总结一些MySQL的常见使用技巧,...

  • mysql查询优化技巧

    工作中,经常有运营需求用于统计线上数据,实际场景中两个百万级表联合查询,往往会大大消耗查询时间。针对此问题,解决思...

  • MySQL查询技巧2

    注:MySQL8 中支持窗口函数(window functions) 在WHERE子句中引用别名列:将含有别名的列...

  • MySQL查询技巧3

    1.查询多列数据的最大值 CASE WHEN 方式 转换行格式后使用MAX函数 使用GREATEST函数 2.排序...

  • 2018-03-20

    MYSQL查询语句 MYSQL复杂操作语句 MYSQL多表查询方法 函数部分

  • 高性能的索引策略

    MySQL查询基础-查询执行过程 MySQL聚簇索引 MySQL覆盖索引 MySQL索引扫描排序 MySQL冗余和...

  • MySQL学习——查询缓存

    MySQL查询缓存简介 MySQL查询缓存是MySQL将查询返回的完整结果保存在缓存中。当查询命中该缓存,MySQ...

  • Mysql 慢查询日志

    Mysql 慢查询日志 慢查询日志 MySQL的慢查询日志是MySQL提供的一种日志记录,它用来记录在MySQL中...

网友评论

      本文标题:MySQL查询技巧

      本文链接:https://www.haomeiwen.com/subject/oyrupqtx.html