PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, February 11, 2022

[FIXED] how to select all within a category if at least one falls within range

 February 11, 2022     lamp, mysql, php, sql     No comments   

Issue

I'm using MySQL inside PHP.
I have an SQL table that looks something like this:

id | category_id | date
-----------------------------
1  | 3           | 2012-09-12
2  | 4           | 2012-10-25
3  | 3           | 2012-10-12
4  | 3           | 2012-10-02
5  | 4           | 2012-11-03
6  | 3           | 2012-11-02

I'm trying to figure out how can select all dates of the given category if at least one falls within the specified date range, otherwise select none.
For example:
If the date range is from 2012-09-01 to 2012-09-31, then the query should return all rows for category 3 and none for category 4.

Is there a way do this in a single query ?

Thanks!


Solution

You do this with a join or in clause:

select t.*
from t join
     (select distinct category_id
      from t
      where date between <datefrom> and <dateto>
     ) tc
     on t.category_id = tc.category_id
order by t.category_id, date


Answered By - Gordon Linoff
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing