相互關聯子查詢在專案中的用法

2021-09-08 00:05:07 字數 1883 閱讀 9147

這3個月一直在做公司的**系統的新功能開發和一些效能改版,經常性的遇見查詢某個地區某個交易品下的最近一天的**。在這裡面用到乙個表md_historyprices是儲存歷史**記錄。

第一種解決方式:用臨時表:

1

with temp_2 as(

2select areaid ,goodsid,min(pricedate) as pricedate from md_historyprices group

by areaid,goodsid

3 )4

select pp.*

from md_historyprices pp , temp_2 tt where pp.areaid = tt.areaid and pp.goodsid = tt.goodsid and

convert(varchar(10), pp.pricedate,120)=

convert(varchar(10),tt.pricedate,120)

第二種解決方式:相互關聯的子查詢:

1

select

*from md_historyprices pp where pp.pricedate = (select

min(ss.pricedate) from md_historyprices ss where ss.areaid =pp.areaid and ss.goodsid = pp.goodsid)

如果從效能上面考慮,第二種解決方式效能高

專案中生成原始**有個需求,用最近一天的**來生成今天(某個使用者、地區和交易品下)的**,如果最近一天不存在,那麼今天這個使用者交易品和地區的**就是0;

1

with temp_1 as(

2select id as goodsid from md_goods where typeid =

13 ),

4 temp_2 as(

5select rr.adminuserid,rr.goodsid,rr.areaid,rr.percentage from md_pricerule rr left

join temp_1 tt on1=

1where rr.percentage>

0and rr.goodsid = tt.goodsid

6 )7

select tt.adminuserid,tt.areaid,tt.goodsid,isnull(pp.guideprice,0),getdate() as guideprice from temp_2 tt left

join md_historyprices pp on tt.areaid= pp.areaid and tt.goodsid = pp.goodsid and

convert(varchar(10),pp.pricedate,120)=(

8select

convert(varchar(10),max(pricedate),120) from md_historyprices p1

9where p1.areaid=pp.areaid and p1.goodsid = pp.goodsid and

convert(varchar(10),p1.pricedate,120)<

convert(varchar(10),getdate(),120)

10 )

查詢每個地區的最早一天的**資訊:

1

select aa.cnname , isnull((select

min(pp.pricedate) from md_historyprices pp where pp.areaid = aa.id),getdate()) from md_areainfo aa

sqlalchemy的關聯子查詢

sqlalchemy也算是用過好幾年了,不過一直都用著其中相對簡單的一小部分,最近寫個程式碰到個問題,需要作乙個關聯子查詢,類似這樣的sql語句 select master.select count from detail where detail.parentid master.id and de...

Springdata redis在專案中的使用

org.springframework.data spring data redis 1.0.3.release log4j log4j org.slf4j slf4j log4j12 spring維護的使用redis用到的bean rediskeyutils類 public class redis...

子查詢IN的用法

今天我們要介紹的是子查詢 子查詢大家應該都不陌生啦,在很多地方可以使用到的 首先我們來總結一下 sql子查詢可以用在哪些地方 子查詢的位置 select 子查詢 from 子查詢 where 子查詢 insert table columns 子查詢 delete table from 子查詢 whe...