0

我想获取常规客户记录的列表。任何人都可以帮助我在 mysql 查询中获取常规客户记录。

常客记录定义:过去3个月单月下单的客户称为常客。

即:客户 A 在 6 月、7 月和 8 月下订单,称为常规,但如果他在 5 月、7 月和 8 月下订单,则它不是常客。

在我的表格列表之后:

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`)
) 
4

3 回答 3

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 引擎和外键约束而不是注释。

于 2013-10-31T08:13:33.533 回答
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';}
};
};
于 2013-10-31T09:17:16.900 回答
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
于 2013-10-31T08:19:28.820 回答