简体   繁体   中英

Two MySQL queries in one, with the second query based on first query

I am struggling with this one.

I have a table called customers, and a table called sales. I want to be able to list for example, all the customers with who have sales from 31 Dec 2010 and earlier - however at the same time exclude the customer if the was a sale made after 31 Dec 2010.

At the moment I have

SELECT * FROM sales WHERE date <= '2010-12-31 23:59:59' ORDER BY sale_id DESC

Which selects the sales on or before my set date.

Then I have another query

SELECT * FROM sales WHERE customer_id='$result1[customer_id]' AND date >= '2010-12-31 23:59:59'

This now finds the sales using the customer_id value from the original query to find which customers have sales after the my search date. I then use a variable if this second query returns a result, for example..

$query2 = mysql_db_query($dbname, "SELECT * FROM sales WHERE customer_id='$r1[customer_id]' AND date >= '2010-12-31 23:59:59'");
$counted = mysql_num_rows($query2); 
if($counted > 0){
    $hidesale="do";
}

which stops the original query from displaying a result.

However this obviously can take some time as it needs to be select every sale before 31 Dec 2010 then run a second query under that sale to find it out if the same customer has any future sales determining if it should be shown or not.

Is it possible to get the above into a single MySQL query, that way I can also limit results to create a page system so that all the results aren't on a single page?

You can select customers who have sales before 2010-12-31 that doesn't have any sales after 2010-12-31 by using NOT EXISTS like below

SELECT * FROM sales s1 WHERE date <= '2010-12-31 23:59:59'
AND NOT EXISTS(SELECT customer_id FROM sales s2 
                 WHERE s2.customer_id = s1.customer_id
                 date > '2010-12-31 23:59:59')
ORDER BY sale_id DESC

or you can use LEFT JOIN solution

SELECT s1.*
FROM sales s1
LEFT JOIN sales s2
ON (s1.customer_id = s2.customer_id AND s2.date > '2010-12-31 23:59:59')
WHERE s1.date <= '2010-12-31 23:59:59'
AND s2.customer_id IS NULL
ORDER BY s1.sale_id DESC

to speed things up you can index customer_id column and date column and sale_id column by using

CREATE INDEX sales_customer_id_index ON sales(customer_id);
CREATE INDEX sales_date_index ON sales(date);
CREATE INDEX sales_sale_id_index ON sales(sale_id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM