sql >> Database >  >> RDS >> Mysql

Joins retourneren niet de juiste resultaten. Wat doe ik verkeerd?

Wanneer u functies zoals tellen, som, enz. gebruikt, moet u een group by-clausule toevoegen om de groepering van de resultaten te regelen:

select 
    concat(u.first_name, ' ', u.last_name) as name, 
    u.skill, 
    ut.name as team_name,
    (count(if(a.tech_id = u.user_id AND a.qc_id = 0 AND a.status = 2,1,0))) AS assigned_scopes,
    (count(if(a.tech_id = u.user_id  AND a.qc_id > 0 AND a.status = 3,1,0))) AS assigned_qa,
    (count(if(a.assignment_id=o.assignment_id and a.tech_id = u.user_id  AND a.status = 2 AND a.qc_id = 0 and o.class_id= 3,1,0))) AS assigned_canvass,
from am_ts_order o 
left join am_ts_assignment a
    ON a.assignment_id=o.assignment_id
left join am_user u
    ON a.tech_id=u.user_id
left join user_team ut
    ON u.user_team_id = ut.user_team_id
where u.user_role_id = 15
    and u.user_team_id = ut.user_team_id
order by u.first_name asc
group by a.tech_id

UPDATE:

Deze zoekopdracht wijzigt de IF-voorwaarden om te testen of een overeenkomende rij is gevonden in enkele van de links samengevoegde tabellen:

select 
    concat(u.first_name, ' ', u.last_name) as name, 
    u.skill, 
    ut.name as team_name,
    count(if(
        (NOT a.tech_id IS NULL) AND 
        (NOT u.user_id IS NULL) AND 
        a.qc_id = 0 AND 
        a.status = 2,1,0)) AS assigned_scopes,
    count(if(
        (NOT a.tech_id IS NULL) AND 
        a.qc_id > 0 AND 
        a.status = 3,1,0)) AS assigned_qa,
    count(if(
        (NOT a.assignment_id IS NULL) AND
        a.assignment_id = o.assignment_id AND 
        a.tech_id = u.user_id AND 
        a.status = 2 AND 
        a.qc_id = 0 AND 
        o.class_id= 3,1,0)) AS assigned_canvass,
from am_ts_order o 
left join am_ts_assignment a
    ON a.assignment_id=o.assignment_id
left join am_user u
    ON a.tech_id=u.user_id
left join user_team ut
    ON u.user_team_id = ut.user_team_id
where u.user_role_id = 15
    and u.user_team_id = ut.user_team_id
order by u.first_name asc
group by a.tech_id



  1. hoe te gebruiken (useUnicode=yes characterEncoding=UTF-8) met DBCP

  2. ORA-00900:ongeldige SQL-instructie - bij het uitvoeren van een procedure in oracle 10g

  3. Correcte manier om gegevens in SQL-database op te slaan wanneer kolommen onbekend zijn

  4. Voeg spatie toe aan mysql zoals zoeken