2017-02-24 55 views
0

幾年後,我回到mysql並遇到問題。我有一個可行的查詢,但我失去了如何更好地優化它。在mysql中限制查詢數據

下面是該查詢:

select 
    u.id as 'User', 
    count(distinct tr.id) as Trips, 
    count(distinct ti.id) as 'Trip Items' 
from 
    users u 
inner join 
    user_emails ue on u.id = ue.user_id 
inner join 
    trips tr on tr.user_id = u.id 
inner join 
    trip_items ti on ti.trip_id = tr.id 
where 
    ue.verified = true and ue.is_primary = true 
and 
    tr.created_at between '2017-02-01 00:00:00' and '2017-02-01 00:59:59' 
group by 1 
having Trips < 30 

我基本上需要得到所有行程和行程中的項目數..但只對那些誰在指定日期範圍內30周或更少的旅行用戶。現在,我正在通過將用戶分組結果,然後執行'擁有'來完成該任務。我正在查看數百萬個非索引字段(created_at)的結果。理想情況下,我想只得到1行,總旅行和總旅行項目。但在查詢過程中仍然應用「用戶少於30次」。這可能嗎? :)

只是一個快速編輯,我試着環顧其他解決方案,但我有點失去了我應該找的東西。我不是在尋找解決方案,可能只是「去檢查一下並嘗試」。

回答

1

count(distinct)可能很貴。嘗試在之前加join。我認爲後續作品(假定項目不不同的旅行中共享):

select u.id as `User`, tr.Trips, tr.items 
from users u inner join 
    user_emails ue 
    on u.id = ue.user_id inner join 
    (select tr.user_id, count(*) as Trips, sum(items) as items 
     from trips tr join 
      (select ti.trip_id, count(*) as items 
      from trip_items ti 
      group by ti.trip_id 
      ) ti 
      on ti.trip_id = tr.id 
     where tr.created_at >= '2017-02-01' and tr.created_at < '2017-02-01 01:00:00' 
     group by tr.user_id 
     having trips < 30 
    ) tr 
    on tr.user_id = u.id inner join 
where ue.verified = true and ue.is_primary = true 
group by 1 
+0

我想給這個一去,它看起來像有一些問題,我無法來解決這些問題!看起來這會返回用戶的結果。所以「User | Trips | TripItems」 - 我試圖弄清楚如何將數據恢復爲「Trips | TripItems」,但仍然對每個用戶應用30或更少的行程限制。我會一直試圖擺弄這個,看看我能看到它的領先地位! – LushJ