3

I hope that someone can help me.

I need to search to filter out values in a database. The database has about 14 000 records of Koalas that have come into care.

Each Koala has their own name with a fate that has happened with it.

A small output of the database fields.

I need to extract the koalaName for the Koala that has been Relocated, Rescued, or In Care but eliminate the koalaName if it has been eventually Found Dead.

In the case of the output above Alec is eliminated in the results as he has eventually Died, Euthanased or Found Dead. In the case of Aleta and Alex I just need to get their name once.

This is the query I've been trying to work with.

SELECT `id`, `koalaName`, `fate`
FROM main  A
    WHERE EXISTS
(
    SELECT `id`, `koalaName`, `fate`
    FROM    main  B
    WHERE   A.koalaName = B.koalaName
    AND     B.`fate` REGEXP 'Released|Relocated|Care'
)
AND NOT EXISTS 
(
    SELECT `id`, `koalaName`, `fate`
    FROM    main  B
    WHERE   A.koalaName = B.koalaName
    AND     B.`fate` REGEXP 'Died|Euth|Dead'
)

I just don't seem to be able to get the result to output the koalaName as a single value instead of returning multiple values

e.g. Alex should only appear once.

Many thanks in advance, I think its simple but I just don't seem to be able to do it.

1 Answer 1

3
SELECT koalaName
FROM main  
GROUP BY koalaName
HAVING SUM( fate IN ('Released', 'Relocated', 'Care') ) > 0
   AND SUM( fate = 'Found Dead') = 0
2
  • With the current fires, let us know if you need performance optimization of this query.
    – danblack
    Jan 1, 2020 at 22:02
  • Thanks Dan, just what I needed, cut the execution time down from 7 sec's to 0.11.
    – Rod-Miller
    Jan 2, 2020 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.