Understanding Cascade Left Joins and Writing Complex Queries

news2024/9/24 17:21:28

文章目录

    • a left join b left join c
    • user case
    • sql query execution order

In SQL, the left join is a powerful tool for combining data from multiple tables based on a common column. In this blog post, we will explore the concept of cascade left joins, providing clear explanations and examples to help you grasp this important technique. Additionally, we will delve into writing complex queries, enabling you to tackle more advanced data retrieval tasks with confidence.

a left join b left join c

The basic each join knowledge, pelase refer https://zhuanlan.zhihu.com/p/29234064

let’s give an example:

  • table total: total student in one school, includes two columns student id and room id, named id and room.
  • table active: active student who go to library in the past 30 days, also includes same two columns.
  • table paid: paid student who paid for library to get static seat in library in the past 30 days, also includes same two columns.

Create table:

CREATE TABLE IF NOT EXISTS `total` (
  `id` int(6) unsigned NOT NULL,
  `room` varchar(200) NOT NULL,
  PRIMARY KEY (`id`,`room`)
) DEFAULT CHARSET=utf8;
INSERT INTO `total` (`id`, `room`) VALUES
  ('1', '103'),
  ('2', '103'),
  ('3', '103'),
  ('4', '104'),
  ('5', '104'),
  ('6', '105'),
  ('7', '107');

CREATE TABLE IF NOT EXISTS `active` (
  `id` int(6) unsigned NOT NULL,
  `room` varchar(200) NOT NULL,
  PRIMARY KEY (`id`,`room`)
) DEFAULT CHARSET=utf8;
INSERT INTO `active` (`id`, `room`) VALUES
  ('1', '103'),
  ('2','103'),
  ('5', '104');

CREATE TABLE IF NOT EXISTS `paid` (
  `id` int(6) unsigned NOT NULL,
  `room` varchar(200) NOT NULL,
  PRIMARY KEY (`id`,`room`)
) DEFAULT CHARSET=utf8;
INSERT INTO `paid` (`id`, `room`) VALUES
  ('1', '103'),
  ('5', '104');

So what’s the output of a left join b left join c ? Before get answer, please understand:

  • A LEFT JOIN B: This indicates that table A is the left table, and table B is the right table. The left join between A and B returns all rows from table A, along with any matching rows from table B. If there is no match, the columns from table B will contain NULL values.
  • A LEFT JOIN B LEFT JOIN C: This extends the previous left join to include table C. In this case, the left join between A and B is performed first. Then, the result of that join is left joined with table C. This means that all rows from table A are preserved, along with any matching rows from table B and C. Again, if there is no match, the columns from the respective tables will contain NULL values.

let’s see, http://sqlfiddle.com/#!9/5911603/14/0

select
  total.*,
  active.*,
  paid.*
from
  total
  left join active on total.id = active.id
  left join paid on active.id = paid.id

if changed to left join paid on active.id = paid.id to left join paid on total.id = paid.id, there is no different.
在这里插入图片描述

user case

Let’s implement this case, want to know how many student count per room with different student type

  • inactive_student: how many student is inactive student to use library, should be total left join active on total.id = active.id where active.id is NULL
  • paid_active_student: how many student is paid active student to use library, should be active left join paid on active.id = paid.id where paid.id is not NULL
  • not_paid_active_student: how many user is not paid active student to use library, should be active left join paid on active.id = paid.id where paid.id is NULL

How to achieve above case by one sql query, let’s understand step by step.

sql: http://sqlfiddle.com/#!9/5911603/3/0

IMPORTANT: the conditions within the CASE WHEN statement are evaluated in order, and once a condition evaluates to true, the corresponding result is returned, and the subsequent conditions are not evaluated.

select
  total.id as id,
  total.room as room,
  (
    case 
      /**
      after run first when: active.id is NULL then 'inactive_student', the rest of users are active student. 
      in the following two when, can split into paid_active_student and not_paid_active_student
      **/
      when active.id is NULL then 'inactive_student'
      when paid.id is NOT NULL then 'paid_active_student'
      else 'not_paid_active_student'
    end
  ) AS student_type
from
  total
  left join active on total.id = active.id
  left join paid on active.id = paid.id

在这里插入图片描述
Then based on above result to group by to know per room student type.

sql: [http://sqlfiddle.com/#!9/5911603/13/0](http://sqlfiddle.com/#!9/5911603/13/0

select
  total.room as room,
  (
    case
      /**
      orderly to match the result
      **/
      when active.id is NULL then 'inactive_student'
      when paid.id is NOT NULL then 'paid_active_student'
      else 'not_paid_active_student'
    end
  ) AS student_type,
  count(total.id) as total_student
from
  total
  left join active on total.id = active.id
  left join paid on active.id = paid.id
group by
  room,
  student_type
order by
  room,
  student_type

在这里插入图片描述

sql query execution order

for better understand above use case, let’s talk about sql query execution order. If you are familar with it, please skip.

In SQL, the order of execution of a query is generally as follows:

  1. FROM clause: This specifies the tables or views involved in the query and sets up the initial result set.

  2. JOIN clause: If there are any join operations specified in the query, the join conditions are evaluated, and the appropriate rows are combined from the joined tables.

  3. WHERE clause: This filters the rows from the result set based on the specified conditions.

  4. GROUP BY clause: If grouping is specified, the result set is divided into groups based on the specified grouping columns.

  5. HAVING clause: This filters the groups from the result set based on the specified conditions.

  6. SELECT clause: This selects the desired columns from the result set.

  7. DISTINCT keyword: If present, duplicate rows are eliminated from the result set.

  8. ORDER BY clause: The result set is sorted based on the specified columns and sort order.

  9. LIMIT or OFFSET clauses: If specified, the result set is limited to a certain number of rows or skipped by a certain number of rows.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/758296.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

面试之MySQL中的mvcc

首先需要知道什么是 MVCC? MVCC 多版本并发控制。MVCC就是通过数据行的多个版本管理来实现数据库的并发控制。这项技术是的InnoDB的事务隔离级别下执行一致性读 有了保证。换言之,就是为了查询一些正在被一个事务更新的行。并且可以看到他们被更新之前的值。查询在…

【excel细碎小知识点】

目录索引 &符号的用法:实例演示: 数字显示和位数的区别:分列功能的妙用:什么叫做常规类型: &符号的用法: **连接字符串:**转化后都是文本字符串类型。你可以通过修改数据类型进行更多可能的操作 实…

高等数学❤️第一章~第二节~极限❤️极限的概念与性质~极限的性质详解

【精讲】高等数学中极限的性质解析 博主:命运之光的主页 专栏:高等数学 目录 【精讲】高等数学中极限的性质解析 导言 一、基本性质 二、四则运算 三、极限存在性 四、唯一性 五、其他性质 必需记忆知识点 例题(用于熟悉高等数学中…

wordpress怎么更改主题自带的页脚或设置不显示?

本文直接提供改原主题代码的方式进行修改 首先我们进入站点的后台,依次点击外观---->主题文件编辑器 然后确定自己的主题是不是想要更改的,之后找到footer.php文件进行修改 可以自己去找一些合适的主题代码复制进去 如果想要不显示,可以…

《面试1v1》大厂的Kafka使用场景

🍅 作者简介:王哥,CSDN2022博客总榜Top100🏆、博客专家💪 🍅 技术交流:定期更新Java硬核干货,不定期送书活动 🍅 王哥多年工作总结:Java学习路线总结&#xf…

按键控制led变化

文章目录 按键控制led变化一、简介二、代码三、仿真代码四、仿真结果五、总结 按键控制led变化 一、简介 使用按键控制开发板上一个led灯的亮灭,当按键按下的时候led灯就亮,当再一次按下按键的时候led就不亮了。由于按键存在抖动,按键松开的…

linux中常见命令(1)

目录 1. less命令 2. cut 命令 3. head和tail命令 4. awk命令 5. tr命令 6. sed 命令 7. uniq 命令 1. less命令 用法&#xff1a;less [option]<filename>##同时打开多个文件 less <filename1> <filename2> <filename3> 点按“q”退出less。利…

再开源一款轻量内存池

前两天已开源线程池&#xff0c;开源一款轻量线程池项目&#xff0c;本节继续开源另一个孪生兄弟&#xff1a;内存池。 本节的线程池与内存池代码解析会在我的星球详细讲解。 内存池&#xff1a;https://github.com/Light-City/light-memory-pool 线程池&#xff1a;https://gi…

Vue-组件基础(上)

一、目标 能够说出什么是单页面应用程序和组件化开发能够说出.vue单文件组件的组成部分能够知道如何注册vue的组件能够知道如何声明组件的props属性能够知道如何在组件中进行样式绑定 二、目录 单页面应用程序vite的基本使用组件化开发思想vue组件的构成组件的基本使用封装组…

await、async、事件循环(宏任务、微任务队列执行顺序)

1 async、await 2 浏览器进程、线程 3 宏任务、微任务队列 4 Promise面试题解析 5 throw、try、catch、finally 异步函数-异步函数的写法 // 普通函数// function foo() {}// const bar function() {}// const baz () > {}// 生成器函数// function* foo() {}// 异步函…

效果超过deepsort,yolov5+bytetrack

目录 1. Motivation 2. BYTE 3. ByteTrack 4.完整代码实现 ByteTrack: Multi-Object Tracking by Associating Every Detection Box 沿着多目标跟踪&#xff08;MOT&#xff09;中tracking-by-detection的范式&#xff0c;我们提出了一种简单高效的数据关联方法BYTE。 利用…

git : 从入门到进阶(实战问题对策)

目录 0. 前言 1. git stash: 暂时保存本地修改 0. 前言 记录日常git使用过程中碰到的一些常见问题的解决&#xff0c;以及一些常用技巧。作为自己作为git使用者的从入门到进阶的成长过程。不求完备但求简洁实用。动态更新。。。 1. git stash: 暂时保存本地修改 多人工作的项…

Linux自主学习 - 多线程的创建(#include<pthread.h>)

备注&#xff1a;vscode通过ssh连接虚拟机中的ubuntu&#xff0c;ubuntu-20.04.3-desktop-amd64.iso 函数pthread_create() // pthread.h中的函数pthread_create()extern int pthread_create (pthread_t *__restrict __newthread, // 线程标识符const pthread_attr_t *…

【039】掌握Vector容器:C++中最强大的动态数组

掌握Vector容器&#xff1a;C中最强大的动态数组 引言一、vector容器概述二、vector的数据结构三、vector常用的API操作3.1、vector构造函数3.2、vector常用的赋值操作3.3、vector的大小操作3.4、vector存取数据操作3.5、vector插入和删除操作 四、vector的未雨绸缪机制五、巧用…

数据库应用:CentOS 7离线安装PostgreSQL

目录 一、理论 1.PostgreSQL 2.PostgreSQL离线安装 3.PostgreSQL初始化 4.PostgreSQL登录操作 二、实验 1.CentOS 7离线安装PostgreSQL 2.登录PostgreSQL 3.Navicat连接PostgreSQL 三、总结 一、理论 1.PostgreSQL &#xff08;1&#xff09;简介 PostgreSQL 是一个…

vue3 -- mitt 插件使用

介绍 mitt插件是Vue3中的一种第三方总线插件,它可以用于在组件之间进行通信。相比于Vue实例上的EventBus,mitt.js足够小,仅有200bytes,支持全部事件的监听和批量移除,它还不依赖Vue实例,所以可以跨框架使用,React或者Vue,甚至jQuery项目都能使用同一套库 . 使用 1:下载插…

Interactive Image Segmentation

Focused and Collaborative Feedback Integration for Interactive Image Segmentation CVPR 2023 清华 Interactive image segmentation aims at obtaining a segmentation mask for an image using simple user annotations. During each round of interaction, the segment…

windows打开此类文件前总是询问怎么解决

打开此类文件前总是询问怎么解决这个一直提示的问题呢&#xff1f; 下面来教大家一个方法杜绝再提示&#xff1a; 开始 --> 运行 --> gpedit.msc (组策略) --> 用户配置 --> 管理模板 --> windows组件 --> 附件管理器 --> 右击 "中等危险文件类型的包…

再学JavaScript

九、常见的运算符 两个等号只判断值&#xff0c;三个等号判断值和类型是否相等 逻辑运算符 注意&&和& ||和| 短路 赋值运算符 自加自减运算符 三目运算符 移位运算符 十、JavaScript的数据类型转换 假如用默认值10&#xff0c;控制台结果就是1035&#xff08…

学生管理系统--java+mysql

学生管理系统 简介 练习&#xff1a;完成学生信息的增删查改&#xff08;根据id&#xff09;&#xff0c;项目进行了三层架构进行创建。 pojo层&#xff0c;dao层&#xff0c;service层&#xff0c;utils层&#xff0c;程序入口&#xff1b; 1.pojo层 实体层 数据库在项目…