简体   繁体   中英

MySQL query optimization. Many SELECT + INNER JOIN

I have next table structure: Games - contains base games info (sport events), Bets - bet variations (team a wins, team b wins etc), Votes - user choises of bet variations.

Next query shows list of all last bet variations for all not started games. Some bets in list also contain some info if current user voted for it.

Inserted selects used for detect next: 1 - is user already voted for this bet?, 2 - get user's choise (yes\\no), 3 - get user's vote amount.

SELECT bets.*, games.Time, games.TA, games.TB, 
  (SELECT COUNT(*) FROM votes WHERE BID=bets.BID AND UID=$UserID) AS Vt, 
  (SELECT YN FROM votes WHERE BID=bets.BID AND UID=$UserID) AS yn,
  (SELECT Pt FROM votes WHERE BID=bets.BID AND UID=$UserID) AS Pt
FROM bets
LEFT JOIN games ON games.GID = bets.GID
WHERE games.Yes=0 AND bets.Dl=0
ORDER BY bets.Time DESC

How can i optimize it? How to get votes.YN and votes.Pt in one query?

Your left join is useless, because you are using a value in the second table. So, I'll change it to inner join for clarity.

In addition, the subqueries for YN and PT have no aggregation, so it would seem that they could return more than one row. I'm assuming there should be a sum() .

Then, I am moving the three correlated subqueries into the from clause. This requires aggregating by bid :

SELECT bets.*, games.Time, games.TA, games.TB,
       coalesce(v.vt, 0) as vt, coalesce(v.yn, 0) as yn, coalesce(v.pt, 0) as pt
FROM bets inner join
     games
     ON games.GID = bets.GID left join
     (select bid, count(*) as vt, sum(yn) as yn, sum(pt) as pt
      from votes v
      where UID=$UserID
      group by bid
     ) v
     on v.bid = bets.bid
WHERE games.Yes=0 AND bets.Dl=0
ORDER BY bets.Time DESC;

EDIT:

Let me point out that this may or may not provide improved performance (depending on things like the selectivity of the where clause). With a left outer join that keeps all the rows from bets , it probably would be better.

Adding the following index should fix the original version of the query: votes(bid, uid) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM