0

特定の日付範囲に複数のカテゴリのそれぞれからいくつのアイテムが表示されるかを判断するために、MySQL クエリを作成しています。私の最初の試みは次のようになりました:

select Title, 
  (select count(*) from entries where CategoryID=1
    and Date >= @StartDate and Date <= @EndDate) as Cat1,
  (select count(*) from entries where CategoryID=2
   and Date >= @StartDate and Date <= @EndDate) as Cat2,
  (select count(*) from entries where CategoryID is null
   and Date >= @StartDate and Date <= @EndDate) as UnkownCategory
from entries
  where Date >= @StartDate and Date <= @EndDate

テーブルは非常に大きく、クエリをリファクタリングして高速化したいと考えていますが、方法がわかりません.GROUP BY/HAVINGステートメントを使用してこれを書き直すことができますか、それとも別の方法がありませんか?

編集:サンプル結果セット - 次のようなもの:

Title | Category 1 Total | Category 2 Total | Unknown Category Total
ABC     1                  3                  0
DEF     2                  7                  2
4

3 に答える 3

3
select Title, SUM(CategoryID=1) as Cat1, SUM(categoryID=2) as Cat2,
SUM(categoryID IS NULL) as UnknownCategory
FROM entries
WHERE Date BETWEEN @StartDate AND @EndDate
GROUP BY Title

sum() 関数に式を貼り付けることができます: true は 1 に等しく、false は 0 に等しくなります。また、少し高速な BETWEEN 演算子を使用しました。

別の結果レイアウトを返す代替案ですが、概念的には少し単純です。

select Title, CategoryID, count(*)
from entries
WHERE Date BETWEEN @StartDate AND @EndDate
group by Title, CategoryID
于 2009-02-04T16:02:32.837 に答える
0
Select COUNT(*), sTitle, CategoryID FROM entries 
WHERE Date >= @StartDate and Date <= @EndDate 
GROUP BY CategoryID, sTitle
于 2009-02-04T15:41:17.277 に答える
0

次のように、カテゴリ ID でグループ化してから、having ステートメントを使用して特定のカテゴリを除外するのはどうでしょうか。

select CategoryID, count(*) 
from entries 
where Date >= @StartDate AND Date <= @EndDate
group by CategoryID
having CategoryID = 1 or CategoryID = 2 or CategoryID is null

カテゴリごとに複数のタイトルがある場合は、両方のフィールドでグループ化できます。

select Title, CategoryID, count(*) 
from entries 
where Date >= @StartDate AND Date <= @EndDate
group by Title, CategoryID
having CategoryID = 1 or CategoryID = 2 or CategoryID is null
于 2009-02-04T15:51:13.967 に答える