SQL查找是否“存在“,别再count了!

Anaconda镜像源切换全攻略:从清华源到恢复默认设置的完整流程 本文详细介绍了Anaconda镜像源的管理与优化,重点讲解了如何配置清华源以提升国内下载速度。内容涵盖镜像源工作原理、清华源详细配置步骤、多源管理策略、常见问题排查以及如何安全恢复默认设置,帮助用户构建完整的镜像源管理体系。 阅读详情

根据某一条件从数据库表中查询 『有』与『没有』,只有两种状态,那为什么在写SQL的时候,还要SELECT count(*) 呢?无论是刚入道的程序员新星,还是精湛沙场多年的程序员老白,都是一如既往的count。

目前多数人的写法

多次REVIEW代码时,发现如现现象:业务代码中,需要根据一个或多个条件,查询是否存在记录,不关心有多少条记录。普遍的SQL及代码写法如下

SQL写法

SELECT count(*) FROM table WHERE a = 1 AND b = 2

Java写法

int nums = xxDao.countXxxxByXxx(params);
if ( nums > 0 ) {
  //当存在时,执行这里的代码
} else {
  //当不存在时,执行这里的代码
}

是不是感觉很OK,没有什么问题

优化方案

推荐写法如下:

SQL写法

SELECT 1 FROM table WHERE a = 1 AND b = 2 LIMIT 1

Java写法

Integer exist = xxDao.existXxxxByXxx(params);
if ( exist != NULL ) {
  //当存在时,执行这里的代码
} else {
  //当不存在时,执行这里的代码
}

SQL不再使用count,而是改用LIMIT 1,让数据库查询时遇到一条就返回,不要再继续查找还有多少条了 业务代码中直接判断是否非空即可

总结

根据查询条件查出来的条数越多,性能提升的越明显,在某些情况下,还可以减少联合索引的创建。

C# WinForm上位机:从串口调试工具到智能温控系统(Modbus RTU协议实战+完整源码) 做工业上位机开发时,我们常从串口调试工具入手:验证设备通信、查看数据帧,但面对实际场景(比如温控、电机控制),单纯的“收发数据”远远不够——需要解析工业标准协议(如Modbus RTU)、实时监控关键指标、实现自动化控制逻辑,还要有稳定的UI交互和数据记录。串口调试工具能收发数据,但看不懂Modbus RTU帧(地址、功能码、寄存器、CRC校验);想控制温控设备(如加热器、风扇),但不知道如何通过Modbus写入控制指令;手动调节目标温度时,温度波动大,需要PID算法实现精准控温,但不会集成; 阅读详情

相关推荐

京东风控算法工程师带你解读Action Model-精细化运营(上篇)

电影《蝴蝶效应》中,男主拥有回到童年改变过去的能力,虽然在剧中男主一次次穿越时空拯救世界,但由于他无法预见自己做出的抉择对未来产生的其他影响,最终还是没能阻止悲剧的发生。可见,一个好的决策需要衡量其对未来产生的影响。JDD风控算法团队本期为大家解惑最优决策难题的解决方法-Action Model。

JDD风控算法的博客 1920

java判断数据库中是否存在某张表

connection.getMetaData.getTables(null,null,tableName,null);

菲律宾铁猴子的博客 962

文华财经公式编程:麦语言简介及基础语法

文华财经公式语言(麦语言)是一种专门用于金融领域的编程语言,它是由文华财经公司开发的。提供了丰富的金融计算函数和数据处理功能,可以用于金融市场的数据分析、模型建立和交易策略的开发。例1:A:CLOSE;// 定义变量A为收盘价(盘中k线没有走完的时候A为最新价)。例2:MA5:=MA(C,5);// 定义收盘价的5周期均线(C为CLOSE简写)。例3:A:=REF(C,1);// 取得前一根k线的收盘价。

超哥量化的博客 1万+

SQL 查找只存在于一个表中的数据

如果你所使用的数据库管理系统没有提供差集函数,那么就要采用 MySQL 和 SQL Server 解决方案介绍的子查询技巧。SQL 查找只存在于一个表中的数据,你希望从一个表(可以称之为源表)里找出那些在某个目标表里不存在的值。关联子查询指的是外层查询执行后获得的结果集会被内层子查询引用。运算符获取第一个结果集的数据,然后从中删除第二个结果集的数据。值影响的替代方案(回到“问题”部分给出的那个原始查询语句)。表中“不存在于”或“未被包含在”子查询结果集里的所有的。当然,之所以能这样做,是因为示例数据中的。

m0_67621290的博客 1054

NPP/VIIRS夜间灯光数据:从下载到应用的完整指南

本文提供了NPP/VIIRS夜间灯光数据从下载、处理到应用的完整实战指南。详细介绍了如何从官方源获取数据、解读文件结构、进行坐标校正与数据清洗,并深入探讨了其在城市扩张监测、社会经济指标估算、重大事件影响评估等领域的核心应用。文章旨在帮助研究者与从业者快速掌握这一强大的空间数据,将其转化为研究中的实用工具。

gpu4optimizer的博客 882

卡方检验的隐藏逻辑:为什么正态分布的平方和如此重要?

本文深入探讨了卡方检验的核心逻辑,揭示了正态分布平方和在统计检验中的重要性。通过分析卡方分布与伽马分布的关系,以及实际应用案例,帮助读者理解卡方检验的原理、局限及高级应用场景,为数据分析提供有力工具。

3a9bq4r8t2y的博客 211

SQL优化——查找数据是否存在

原因:SQL 不再用count,改用LIMIT 1,让数据库可以在查到第一条数据之后就返回,不再继续查找是否有更多数据,业务代码只需要判断是否非空就可以了。

Wen先森的博客 3400

Centos 7 Linux 安装单机 Hadoop(HDFS):下载、安装、配置、测试

本文详细介绍了在 CentOS 7 系统上安装与配置单机 Hadoop(HDFS)的完整流程,涵盖 JDK 环境准备、Hadoop 安装包下载与部署、核心配置文件(core-site.xml、hdfs-site.xml 等)修改、SSH 免密登录设置、HDFS 格式化及服务启动,并通过命令行与 Web 界面验证 HDFS 和 YARN 功能,适合 Hadoop 初学者快速搭建本地测试环境。

寒水馨 · 轻量级技术文档 · hanshuixin.org 3247

SQL判断某条记录是否存在

查询条件使用LIMIT 1,当数据库查询时遇到一条就返回。时间复杂度:O(log n)。

qq_41201304的博客 695

数学建模Matlab算法,第七章 对策论

对策论作为研究竞争与决策的数学理论,从零和对策到非常数和对策,为分析各类博弈问题提供了系统框架。其核心要素包括局中人、策略集和赢得函数,通过稳定解、Nash平衡点等概念揭示竞争规律。该理论广泛应用于经济、军事、政治等领域,不仅提供具体分析工具,更改变了决策思维方式,强调在互动中实现理性选择。对策论既揭示了竞争本质,也凸显合作价值,为解决社会矛盾、促进共赢发展提供了重要启示,在全球化背景下将发挥更大作用。

unber的博客 124

C++幂运算全解析:std::pow()函数详解与实战指南

本文详细介绍了C++标准库中的std::pow()函数,包括其基本用法、数学定义和多种重载形式。重点分析了该函数在科学计算、图形处理等领域的实际应用,并提供了性能优化方案如快速幂算法和预计算表。文章还探讨了精度控制、错误处理等关键问题,最后通过一个完整计算器实现展示了综合应用。std::pow()作为基础数学函数,合理使用能显著提升计算效率和代码可靠性。

专注现代C++实战,从核心语法到高性能编程,助力开发者深入掌握系统级编程精髓。 342

存在于一个表而不存在于另一个表中的数据

方法1:  select * from (select distinct  aid from a ) as c    where (select count(1) as num from b where b.bid = c.aid) = 0方法2: select c.aid from (select distinct aid from a) as c left jo

学而不思则罔 3018

Arch Linux 命令大全,值得收藏!

Arch Linux 是一款轻量级、高度可定制的 Linux 发行版,以其简洁和强大的特性深受高级用户喜爱。但对于新手来说,完全掌握 Arch Linux 的操作需要时间和实践。本文将为您详细介绍常用的 Arch Linux 命令,涵盖系统管理、文件操作、用户管理、软件安装与管理、网络配置和磁盘管理等内容,帮助您更高效地使用 Arch Linux。

网络技术联盟站 980

SQL查找是否"存在",别再count了!

点击上方“民工哥技术之路”,选择“设为星标”回复“1024”获取独家整理的学习资料!根据某一条件从数据库表中查询 『有』与『没有』,只有两种状态,那为什么在写SQL的时候,还要SELEC...

民工哥的博客 1495

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

SQL 查找是否"存在",别再 count 了,很耗费时间的!

程序员的成长之路互联网/程序员/技术/资料共享关注阅读本文大概需要 2 分钟。来自:https://zhuanlan.zhihu.com/p/158794137根据某一条件从数据库表中...

良月柒 793

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

SQL 查找是否"存在",别再 count 了!

↓推荐关注↓根据某一条件从数据库表中查询 『有』与『没有』,只有两种状态,那为什么在写SQL的时候,还要SELECT count(*) 呢?无论是刚入道的程序员新星,还是精湛沙场多年的程序...

Python数据之道 351

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

SQL 查找是否“存在“,别再 count 了,很耗费时间的!

目前多数人的写法 优化方案 总结 根据某一条件从数据库表中查询 『有』与『没有』,只有两种状态,那为什么在写SQL的时候,还要SELECT count(*) 呢? 无论是刚入道的程序员新星,还是精湛沙场多年的程序员老白,都是一如既往的count 目前多数人的写法 多次REVIEW代码时,发现如现现象: 业务代码中,需要根据一个或多个条件,查询是否存在记录,不关心有多少条记录。普遍的SQL及代码写法如下 #### SQL写法: SELECT count(*) FROM table WHERE a = 1 .

程序员白楠楠的博客 952

SQL 查找“存在“,别再用 count 了,很耗费时间的!

目录 目前多数人的写法 优化方案 总结 根据某一条件从数据库表中查询 『有』与『没有』,只有两种状态,那为什么在写SQL的时候,还要SELECT count(*) 呢? 无论是刚入道的程序员新星,还是精湛沙场多年的程序员老白,都是一如既往的count 目前多数人的写法 多次REVIEW代码时,发现如现现象: 业务代码中,需要根据一个或多个条件,查询是否存在记录,不关心有多少条记录。普遍的SQL及代码写法如下 SQL写法: SELECTcount(*)FROMtable ...

程序员白楠楠的博客 622
上一篇: 实战整了一个后台服务,真香!
下一篇: 聊一聊MySQL的记录锁、间隙锁与 Next-Key Lock
Java_LingFeng
博客等级 码龄4年 506粉丝 259原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址