Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Optimalisation of MySQL query

Posted on 2008-10-08
1
Medium Priority
?
218 Views
Last Modified: 2013-12-12
I have an mysql table with jobs. This table contains an entry 'insertionDate' which contains the date that a job was insertion.
Now I want to know the amount of jobs that were
- inserted today
- inserted this week
- inserted this month.

How can I do this with only 1 query?

Now I use 3 queries for this. The query for the jobs from last week is:
SELECT
  COUNT( * )
FROM
 jobs
WHERE
 DATEDIFF( NOW(), insertionDate ) < 7

Open in new window

0
Comment
Question by:thijs321
1 Comment
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 2000 total points
ID: 22667654
please check out this:
SELECT count(*) inserted_this_month
 , SUM(case when insertionDate >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) then 1 else 0 end) inserted_last_7_days
 , SUM(case when insertionDate >= CURDATE then 1 else 0 end) inserted_today
FROM jobs
WHERE insertionDate >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) 

Open in new window

0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

963 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question