Home » Php » mysql – Duplicates in left join php mysqli

mysql – Duplicates in left join php mysqli

Posted by: admin February 25, 2020 Leave a comment

Questions:

this query shows duplicate when the rows from both tables are more than 1

$ph_request = $db->fetchRows("SELECT h.*, g.*, h.status as h_status, h.ph_amount as h_ph_amount, h.help_id as h_help_id, h.h_unique_id as h_h_unique_id, h.user_id as h_user_id, h.ph_date as h_ph_date, h.ph_commitment as h_ph_commitment, h.ph_type as h_ph_type,
g.status as g_status, g.user_id as g_user_id, g.getter_tbl_id as g_getter_tbl_id, g.gh_committment as g_gh_committment, g.gh_type as g_gh_type, g.status as g_status, g.method as g_method, g.amount as g_amount,
u.nickname as u_nickname
FROM helper AS h
LEFT JOIN getter_tbl AS g ON h.user_id = '{$user_id}' AND g.user_id='{$user_id}'
LEFT JOIN user AS u ON u.user_id = '{$user_id}'
WHERE h.user_id='{$user_id}' OR g.user_id='{$user_id}' AND h.status='open' OR g.status='open'
GROUP BY h.help_id, g.getter_tbl_id, u.user_id ");
How to&Answers:

For avoid duplicate .. don’t use all (*) operator
and add DISTICNT clause (not group by without aggregation function )

    SELECT DISTINCT 
      , h.status as h_status
      , h.ph_amount as h_ph_amount
      , h.help_id as h_help_id
      , h.h_unique_id as h_h_unique_id
      , h.user_id as h_user_id
      , h.ph_date as h_ph_date
      , h.ph_commitment as h_ph_commitment
      , h.ph_type as h_ph_type
      , g.status as g_status
      , g.user_id as g_user_id
      , g.getter_tbl_id as g_getter_tbl_id
      , g.gh_committment as g_gh_committment
      , g.gh_type as g_gh_type
      , g.status as g_status
      , g.method as g_method
      , g.amount as g_amount
      , u.nickname as u_nickname
FROM helper AS h
LEFT JOIN getter_tbl AS g ON h.user_id =:user_id AND g.user_id=:user_id
LEFT JOIN user AS u ON u.user_id = :user_id
WHERE ( h.user_id=:user_id OR g.user_id=:user_id )
AND  (h.status='open' OR g.status='open')

For avoid unaspected result you should also add proper () for the AND OR clause
and for avoid sqlinjection you should use param and not php var