Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Deekshith's avatar

write subquery with leftjoin

i have a table structures like below,

courses

course_id, course_name, course_code

packages

package_id, course_id, package_name

tests

test_id, course_id, test_name, schedule_date,test_type

test_package_mapping

maping_id, test_id, package_id

user_tests

id, user_id, test_id, user_test_status (4 means completed)

in my project there are n number of courses and each courses has packages and also i have test inventory where i will create all the tests with date and now i will assign test to package so once user purchases the package then mapped tests will be available to purchased user to take the test (MCQ based test)

Now i am trying to get the stats related to these table.

i want to fetch coursedetails, no of tests mapped to all packages present in selected course, user completed tests

i want to write this in query builder as of now i tried like below,

$coursedetail = Courses::join('packages','courses.course_id','=','packages.course_id')
->join('test_package_maping','packages.package_id','=','test_package_maping.package_id')
->join('tests','test_package_maping.test_id','=','tests.test_id')
->join('user_tests','test_package_maping.test_id','=','user_tests.test_id')
->where('courses.course_id',$courseid)
->select(
                DB::raw('count(case when tests.test_type IN ('.$prelimsimplode.') then 1 end) as testscount'),
              DB::raw('count(case when tests.test_type IN ('.$prelimsimplode.') and user_tests.user_test_status = 4 then 1 end) as completedprelimstests'),
                'courses.course_name','courses.course_code','courses.course_type'
            )
          ->withCount('ordersdata')
          ->first();

Example: tests has => 30 records user_tests has => 10000 records

once i ran this code i am getting testscount as 10000 instead of 30.i know when i join with user_tests it will return user_tests table records count but how to write this in subquery so that tests count should not be duplicated. Please help me with this query. Thank you

0 likes
0 replies

Please or to participate in this conversation.