Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Optymalizacja zapytania
matino
post
Post #1





Grupa: Zarejestrowani
Postów: 175
Pomógł: 30
Dołączył: 9.08.2007

Ostrzeżenie: (0%)
-----


Mam tabelę, w której w każdym rzędzie przechowuję m.in. datę utworzenia oraz login.
Jako rezultat ma wyjść tabelka - kolumny loginy, wiersze daty a w środku liczba wystąpień w tabeli dla danej daty i danego loginu:

data | login1 | login2 | suma
2011-06-18 6 7 13
2011-06-19 2 1 3
Razem: 8 8 16

Na tą chwilę zrobiłem to w sposób taki, że pobieram jednym selectem distinct daty, drugim selectem loginy.
Następnie lecę podwójnym foreach i dla każdej daty, wykonuję select count(*) dla każdego loginu.
Takie rozwiązanie jest jednak mało wydajne (przy 12 datach i 9 loginach łączny czas zapytania zajmuje 2 sekundy (IMG:style_emoticons/default/smile.gif) ).

Może ma ktoś wydajniejszy sposób do przetestowania?

Poniżej kod jakby kogoś interesował:
  1. public static function get_cases_by_users($users, $start = NULL, $end = NULL)
  2. {
  3. if (!is_array($users))
  4. {
  5. return NULL;
  6. }
  7. if (empty($start))
  8. {
  9. $start = 0;
  10. }
  11. if (empty($end))
  12. {
  13. $end = 9999999999;
  14. }
  15.  
  16. // Get dates first where cases were generated
  17. $dates = DB::select(array('FROM_UNIXTIME("create_date", \'%Y-%m-%d\')', 'create_date'))
  18. ->distinct('create_date')
  19. ->from(table')
  20. ->where('create_date', 'BETWEEN', array($start, $end + Date::DAY))
  21. ->order_by('create_date')
  22. ->execute()->as_array('create_date');
  23.  
  24. // Count users for calculated dates
  25. $result = array();
  26. foreach ($dates as $date => $value)
  27. {
  28. $result[$date] = array();
  29. foreach ($users as $user)
  30. {
  31. $count = DB::select(array('COUNT("username")', 'total'))
  32. ->from('table')
  33. ->where(array('FROM_UNIXTIME("create_date", \'%Y-%m-%d\')', NULL), 'LIKE', $date . '%')
  34. ->and_where('username', '=', $user)
  35. ->execute()->as_array();
  36. $count = Arr::flatten($count);
  37. $result[$date][$user] = $count['total'];
  38. }
  39. }
  40. return $result;
  41. }
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 29.09.2025 - 12:10