左联接MYSQL查询中的重复项

时间:2020-02-18 03:04:18

标签: mysql

请帮助,我如何删除重复项

每张表上有两行以上时,它们就会重复

(helper)表行增加时(getter_tbl)结果不断重复

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, u.user_id as u_user_id
FROM helper AS h
LEFT JOIN getter_tbl AS g ON h.user_id = g.user_id
LEFT JOIN user AS u ON u.user_id = '{$user_id}'
WHERE h.user_id = '{$user_id}' AND 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 

这是我的代码

foreach($query as $queryRows){
    if($queryRows['g_status'] == 'open'){
      print '
        <div class="block-content block-content-full text-left text-black" style="padding: 10px 15px 1px; ">
        <div class="font-size-sm text-black-op" style=" color: black !important; "><strong>Amount:</strong> '.number_format($queryRows['g_gh_committment'], 0).'</div>
        <div class="font-size-sm text-black-op" style=" color: black !important; "><strong>Balance:</strong> '.number_format($queryRows['g_gh_committment'], 0).'</div>

      ';
    }
    if($queryRows['h_status'] == 'open'){
      print '
        <div class="block-content block-content-full text-left text-black" style="padding: 10px 15px 1px; ">
        <div class="font-size-sm text-black-op" style=" color: black !important; "><strong>Amount:</strong> '.number_format($queryRows['h_ph_amount'], 0).'</div>
        <div class="font-size-sm text-black-op" style=" color: black !important; "><strong>Balance:</strong> '.number_format($queryRows['h_ph_commitment'], 0).'</div>

      ';
    }
}

1 个答案:

答案 0 :(得分:0)

在评论中变得很难清楚-所以我提供了一个潜在答案。

您多次复制user_id。也许这就是您重复结果的原因。

您的SQL语法也可能有错误。我假设您的WHERE子句应为AND(h.status = open或g.status = open)。这样,您想要在这些状态之一处于打开状态时获取用户。

这行吗?

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.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.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,
u.user_id as u_user_id

FROM helper AS h
LEFT JOIN getter_tbl AS g ON h.user_id = g.user_id
LEFT JOIN user AS u ON u.user_id = h.user_id

WHERE 
u.user_id = '{$user_id}' AND 
(h.status='open' OR g.status='open')

GROUP BY h.help_id, g.getter_tbl_id, u.user_id

注意:它将仅返回u_user_id(并且不会在3个不同的变量中返回相同的ID)