MySQL Forums
Forum List  »  Newbie

Re: Combining several queries from Wordpress Database
Posted by: Rick James
Date: December 28, 2014 12:51PM

You are finding out the hard way why Key-Value schema sucks.

SELECT  s.statistic_ref_id,
        sum(s.points) AS TotalPoints,   -- see note
        sr.quiz_id,
        sr.user_id,
        m.name,
        u.user_email,
        fn.meta_value AS FirstName,   -- 3 new lines
        ln.meta_value AS LastName,
        c.meta_value AS Calibre
    FROM  (((`wp_wp_pro_quiz_statistic` AS s
                            LEFT JOIN  `wp_wp_pro_quiz_statistic_ref` AS sr
                                 ON s.statistic_ref_id = sr.statistic_ref_id)
                    LEFT JOIN  `wp_wp_pro_quiz_master` AS m  ON sr.quiz_id = m.id )
            LEFT JOIN  wp_users AS u  ON sr.user_id = u.ID 
          )                     -- added just in case
    JOIN  wp_usermeta AS fn ON fn.id = u.id  AND  fn.meta_key="first_name"   -- 3 new lines
    JOIN  wp_usermeta AS fn ON ln.id = u.id  AND  ln.meta_key="last_name"
    JOIN  wp_usermeta AS fn ON c.id  = u.id  AND   c.meta_key="calibre"
    GROUP BY  s.statistic_ref_id, sr.quiz_id, sr.user_id, m.name, u.user_email
    ORDER BY  s.statistic_ref_id DESC;

Still to be fixed:
* I am unclear on the parentheses in the LEFT JOINs -- perhaps they are ok as shown.
* I am guessing at how to JOIN to wp_usermeta with the user id. (I have no knowledge of this schema.)
* Because of the "LEFT", you _may_ have rows with no "user", hence NULLs for the 3 new columns.
* Check the results; SUM(s.points) _may_ be "wrong" due to the GROUP BY.
* I'm guessing at the field name `meta_value`.
* I'm guessing that you want to display the name and calibre.
* I don't understand where secure_invite_invitation_code fits in. Perhaps you can see the pattern and fix it.

I took the liberty of using "aliases" for all tables -- making the query smaller helps the readability (in my opinion).

If you need to discuss this further, please provide this for each table:
SHOW CREATE TABLE

Options: ReplyQuote


Subject
Written By
Posted
Re: Combining several queries from Wordpress Database
December 28, 2014 12:51PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.