我想完成一個查詢,需要一個計算列使用通過變量傳遞日期引用的子查詢。我不確定我是不是「做對了」,但基本上查詢從來沒有完成,並在幾分鐘內旋轉。這是我的查詢:用戶定義的變量的MySQL子查詢
select @groupdate:=date_format(order_date,'%Y-%m'), count(distinct customer_email) as num_cust,
(
select count(distinct cev.customer_email) as num_prev
from _pj_cust_email_view cev
inner join _pj_cust_email_view as prev_purch on (prev_purch.order_date < @groupdate) and (cev.customer_email=prev_purch.customer_email)
where cev.order_date > @groupdate
) as prev_cust_count
from _pj_cust_email_view
group by @groupdate;
子查詢有inner join
實現自聯接,只有給我的已經在@groupdate
日之前購買的人的數量。該EXPLAIN
低於:
+----+----------------------+---------------------+------+---------------+-----------+---------+---------------------------+--------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+----------------------+---------------------+------+---------------+-----------+---------+---------------------------+--------+---------------------------------+
| 1 | PRIMARY | _pj_cust_email_view | ALL | NULL | NULL | NULL | NULL | 140147 | Using temporary; Using filesort |
| 2 | UNCACHEABLE SUBQUERY | cev | ALL | IDX_EMAIL | NULL | NULL | NULL | 140147 | Using where |
| 2 | UNCACHEABLE SUBQUERY | prev_purch | ref | IDX_EMAIL | IDX_EMAIL | 768 | cart_A.cev.customer_email | 1 | Using where |
+----+----------------------+---------------------+------+---------------+-----------+---------+---------------------------+--------+---------------------------------+
而且表_pj_cust_email_view
的結構是這樣:
'_pj_cust_email_view', 'CREATE TABLE `_pj_cust_email_view` (
`order_date` varchar(10) CHARACTER SET utf8 DEFAULT NULL,
`customer_email` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
KEY `IDX_EMAIL` (`customer_email`),
KEY `IDX_ORDERDATE` (`order_date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1'
同樣,正如我剛纔所說,我真的不知道,這是最好的方式做到這一點。任何批評,方向感謝!
更新
我已經取得了一點進步,現在我做上面的程序上通過所有已知的迭代幾個月,而不是在數據庫個月,提前設定的時間瓦爾。我不喜歡這個。這是我現在得到:
設置中定義的用戶瓦爾
set @startdate:='2010-08', @enddate:='2010-09';
獲取總不同的電子郵件在給定範圍內
select count(distinct customer_email) as num_cust
from _pj_cust_email_view
where order_date between @startdate and @enddate;
獲取的總數在給定範圍之前購買的顧客
select count(distinct cev.customer_email) as num_prev
from _pj_cust_email_view cev
inner join _pj_cust_email_view as prev_purch on (prev_purch.order_date < @startdate) and (cev.customer_email=prev_purch.customer_email)
where cev.order_date between @startdate and @enddate;
其中@startdate
設置爲月初,@enddate
表示該月的範圍結束。
我真的覺得這仍然可以在一個完整的查詢中完成。
查看更新對於目前的解決方案,它返回我正在尋找,但迭代,我希望它在一個完整的查詢。 – philwinkle 2011-02-25 14:56:54
如果您提供了一些樣本輸入數據和一些預期輸出,這將有所幫助。 – Thomas 2011-02-27 05:10:26