I have a database with 2 tables:
Table 1:
CREATE TABLE IF NOT EXISTS `sales` (
`sale_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`sale_total` int(11) NOT NULL,
`sale_date` date NOT NULL,
`sale_status` int(11) NOT NULL,
PRIMARY KEY (`sale_id`)
) ;
Table 2:
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`lastname` varchar(200) NOT NULL,
`mail` varchar(200) NOT NULL,
PRIMARY KEY (`user_id`)
);
I need the following query optimized, so that it does not use subqueries. I this this could be accomplished using joins, but I don't know exactly how.
SELECT name, lastname, mail
FROM users
WHERE user_id IN (
SELECT user_id
FROM sales
WHERE sale_date < '2009-01-01'
AND sale_total >100
AND sale_status =4
)
AND user_id NOT IN (
SELECT user_id
FROM sales
WHERE sale_date >= '2009-01-01'
)