簡體   English   中英

如果至少有一個屬於范圍內,如何選擇一個類別中的所有內容

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

我在PHP中使用MySQL。
我有一個SQL表,看起來像這樣:

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

我試圖弄清楚如果至少有一個屬於指定的日期范圍,如何選擇給定類別的所有日期,否則選擇無。
例如:
如果日期范圍是2012-09-01到2012-09-31,則查詢應返回類別3的所有行,而不返回類別4的所有行。

有沒有辦法在單個查詢中執行此操作?

謝謝!

您可以使用join或in子句執行此操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM