--客戶表
create table TB_Customer
(
ID int identity primary key,
Name nvarchar(10),
Mobile nvarchar(10)
)
--銷售單表
create table TB_Sale
(
ID int identity primary key,
Year int,--年份
CustomerID int,--客戶表外鍵
IsCard bit default(0),--有卡片銷售
IsProduct bit default(0),--有零售
SalePrice decimal(10,2)--銷售額
)
--卡片表
create table TB_Card
(
ID int identity primary key,
Year int,--年份
Statu int, --1、不可以2、可用3、已用
CardNumber nvarchar(20),
CardPrice int,--卡片額度
BuyDiscount decimal(3,2),--購買折扣
CustomerID int,--客戶表外鍵
SaleID int,--銷售單表外鍵
)
上述三張表,其中客戶表的資料10W,銷售單表的資料30W,卡片表的資料500W
目前需要匯總幾個資料:
1、查詢所有客戶的購買額度和卡片的購買額度
2、查詢銷售單中不同狀態卡片的集合
上邊2個方法,我用的是基本的查詢匯總方式
--查詢所有客戶的購買額度和卡片的購買額度
select c.ID,C.Name,c.Mobile,
(select ISNULL(sum(s.SalePrice),0) from TB_Sale s where s.CustomerID=c.ID) as 'SalePrice',
(select ISNULL(sum(case when d.BuyDiscount>0 d.CardPrice*d.BuyDiscount then else d.CardPrice end),0) from TB_Card d where d.CustomerID=c.ID) as 'CardPrice'
from TB_Customer c
--查詢銷售單中不同狀態卡片的集合
select * from TB_Card where Statu=1 and SaleID=@SaleID
select * from TB_Card where Statu=2 and SaleID=@SaleID
select * from TB_Card where Statu=3 and SaleID=@SaleID
我用的方法執行起來比較慢,其中我對TB_Sale中的CustomerID,TB_Card中的Statu、CustomerID、SaleID加了索引。
上述方法執行起來比較耗CPU,執行時間也特別慢,應該怎樣提高查詢速度和性能,需不需要做磁區什么的
uj5u.com熱心網友回復:
客戶有10萬,你要一口氣查10萬條資訊, 即使不關聯其它表, 也快不到哪里吧?索引是在篩選,保留少部分記錄的條件下才有效的, 你全部查, 索引有何意義?
建議:
1. 以空間換時間, 在客戶表中增加欄位, 保存相應的值, 在購買時就更新這些值, 不要等查詢時再來慢慢算。
2. 如果是網站或其他客戶端訪問,增加分頁,每頁幾十條資料即可
uj5u.com熱心網友回復:
用left join 寫吧。 TB_Sale 的CustomerID欄位加索引 TB_Card的 CustomerID欄位也要加索引uj5u.com熱心網友回復:
查集合的那三個陳述句 建一個 SaleID, Statu 兩個欄位的聯合索引。速度應該非常快。另外。不要一次回傳客戶端那么多資料,使用分頁回傳
uj5u.com熱心網友回復:
最理想的方法是按年份磁區,可以參考SQL SERVER HELP選單;沒有哪個客戶厲害到要把幾十萬個資料一條一條看過的,
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/203024.html
標籤:疑難問題
上一篇:ubuntu 安裝 docker 并配置鏡像加速(使用 apt-get 進行安裝)
下一篇:螞蟻集團暫緩上市:致歉投資者
