简体   繁体   中英

PHP & MySQL - LEFT JOIN? SUBQUERY? GROUP BY? - LIMIT 1

I've been stuck on this for a while and am hoping someone will be able to help.

I've made a simple mysql query (see below) which works fine but now I need to change it to retrieve additional data from other tables.

Here are my three tables:

Member Table

  • ID
  • firstName
  • lastName

Certification Table

  • ID
  • memberID
  • courseID
  • certificationDate

Course Table

  • ID
  • courseTitle
  • level

There are a number of courses which members can take. When they do they get a certification which corresponds to the correct member and course.

Courses go up in levels.

I'm trying to list all my members and show their highest certification (according to it's level) and the course title for it.

Not all members have certifications but I still need to retrieve their data too.

I need to adjust the query below to include the user's highest certification and only the highest certification. I'm trying to avoid multiple certifications per member.

Any help would be amazing as I've been trying to solve this for ages. I've tried LEFT JOIN, GROUP BY, subqueries and just can't get my head around it.

Thank you.

// Member Query
$tableMember = $wpdb->prefix . "dmc_diver";
$tableCertifications = $wpdb->prefix . "dmc_certifications";
$tableCourse = $wpdb->prefix . "dmc_course";

$memberQuery = $wpdb->get_results("

    SELECT
    ID,
    firstName, 
    lastName

    FROM 
    $tableMember

");

Here is one method, using a correlated subquery:

select m.*,
       (select max(co.level)
        from certification c join
             course co
             on c.id = co.courseid
        where c.memberid = m.id
       ) as max_level
from members m;

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