开发者

mysql/php unsure how to build specific query

I am using PHP and MySQL. I have two tables, one for customers, and one for sale entries. My goal is to come up with a list of 5 customers who have more than three regular sale entries in the past year, but zero sale entries of any type in the past three months (basically regular customers who have recently stopped buying). At the same time, I would like to grab the date of th开发者_开发知识库e latest sale entry for each of these customers, and also order the list of customers by their latest sale entry date in a descending direction. This should also limit results to 5 customers.

So for simplicity sake, let's say that the 'customer' table looks like this

id, customer_name

and the 'sale_entry' table looks like this

id, customer_id, entry_date, sale_type (can be 0=regular, 1=spot, 2=contract)

The customer_id field in the sale_entry table of course relates to the id field in the customer table. Any ideas on how best to retreive the desired data is welcome.


Accomplished with a few subqueries.

$query = 'SELECT DISTINCT'
    .' customers.id'
    .', customers.customer_name'
    .', (SELECT MAX(x.entry_date) FROM sale_entry AS x WHERE x.customer_id = customers.id) AS last_purchase_date'
    .' FROM customers'
    .' WHERE (SELECT COUNT(x.id) FROM sale_entry AS x WHERE x.customer_id = customers.id AND x.type = 0 AND x.entry_date >= \''.date('Y-m-d', strtotime('-1 year')).'\') > 0'
    .' AND (SELECT COUNT(x.id) FROM sale_entry AS x WHERE x.customer_id = customers.id AND x.entry_date >= \''.date('Y-m-d', strtotime('-3 months')).'\') = 0'
    .' ORDER BY last_purchase_date DESC'
    .' LIMIT 5';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜