2013-10-31 19 views
0

我想獲得常規客戶記錄列表。任何人都可以幫助我在MySQL查詢中獲取常規客戶記錄。如何獲得常規客戶列表

普通客戶記錄認定中的:誰放在月份單爲了讓過去的3個月,呼籲常客一位顧客。

即:客戶對君,七月和八月的地方一個爲了所謂的正規,但如果他下訂單在5月,七月和八月那就不是一個普通客戶。

關注我的表列表:

CREATE TABLE IF NOT EXISTS `customer_mst` (
    `ID` int(11) NOT NULL AUTO_INCREMENT, 
    `firstName` varchar(50) NOT NULL, 
    `lastName` varchar(50) NOT NULL, 
    `email` varchar(150) NOT NULL, 
    `phone` varchar(20) NOT NULL, 
    `dateCreated` datetime NOT NULL, 
    `lastActivity` datetime NOT NULL, 
    `ipAddress` varchar(40) NOT NULL, 
    PRIMARY KEY (`ID`) 
) 

CREATE TABLE IF NOT EXISTS `order_mst` (
    `ID` int(11) NOT NULL AUTO_INCREMENT, 
    `custId` int(11) NOT NULL COMMENT 'FK customer_mst(ID)', 
    `grandTotal` float NOT NULL, 
    `createdDate` datetime NOT NULL, 
    PRIMARY KEY (`ID`), 
    KEY `custId` (`custId`) 
) 
+0

你找誰誰下訂單在過去** **三個月或**任何客戶**三連冠幾個月?這些問題意味着前者,但這個例子適用於後者。 – Mureinik

+0

另外,客戶可以在同一個月內下幾個訂單嗎? – Mureinik

+0

@Mureinik 1)連續最後三個月 2)客戶在任何一個月內沒有任何訂單 – Dipen

回答

1

這是最簡單的方法,但不是最快的:

select * from customer_mst 
where ID in (
    select custId from order_mst 
    where createdDate <= (NOW() - INTERVAL 2 MONTH) and createdDate > (NOW() - INTERVAL 3 MONTH) 
) 
and ID in (
    select custId from order_mst 
    where createdDate <= (NOW() - INTERVAL 1 MONTH) and createdDate > (NOW() - INTERVAL 2 MONTH) 
) 
and ID in (
    select custId from order_mst 
    where createdDate <= NOW() and createdDate > (NOW() - INTERVAL 1 MONTH) 
) 

提示:使用InnoDB引擎和foreign key constraints的意見,而不是嘗試。

+0

在您的查詢中,沒有檢查3個月的連續訂單 –

+0

如果您希望訂單的總數由客戶只需添加此條件:通過計數(order_mst.ID) 秩序但是要注意,使用COUNT()是不是一個好的做法:計數(order_mst.ID)> = 2 或者,你可以下訂單的數量進行排序。您應該將該數字保留在單獨的列中。 –

+0

這是不正確的解決方案導致計數將超過3個單月也不連續 –

0

試試這個

select customer_mst.*,DATEDIFF(now()-order_mst.createdDate) as diff_days 
from customer_mst 
left join order_mst on (order_mst.custId = customer_mst.ID) 
group by customer_mst.ID having diff_days < 90 
+0

在您的查詢中,沒有檢查連續3個月的訂單 –

+0

是的,你的右@ Upendra Chaudhari我錯過了那部分對不起。 – vijaykumar

+0

它會給我3個月前下單的客戶記錄,但我想要客戶記錄誰在過去3個月每個月下單的順序。 :客戶「A」在jun,jul和aug上下了一個要求定期的訂單,但如果他在五月,八月和八月下訂單,那麼它不是常規客戶。 在上述情況下,客戶「A」必須在每個月(jun,jul和aug)下單以成爲常規客戶。 – Dipen

0

效率不高,但

$month1=mysqli_query(select * from customer_mst 
where ID in (
    select custId from order_mst 
    where createdDate <= (NOW() - INTERVAL 2 MONTH) and createdDate > (NOW() - INTERVAL 3 MONTH) 
)); 
$rows=mysqli_num_rows($month1); 
if($rows>0){ 
$month2=mysqli_query(select * from customer_mst 
where ID in (
    select custId from order_mst 
    where createdDate <= (NOW() - INTERVAL 1 MONTH) and createdDate > (NOW() - INTERVAL 2 MONTH) 
)); 
$rows1=mysqli_num_rows($month2); 
if($rows1>0){ 
$month3=mysqli_query(select * from customer_mst 
where ID in (
    select custId from order_mst 
    where createdDate <= NOW() and createdDate > (NOW() - INTERVAL 1 MONTH) 
)); 
$rows2=mysqli_num_rows($month3); 
if($month3>0){ 
echo 'regular customer';} 
}; 
};