0

I'm running the a query to return all results where a serial number has been entered more than once as follows:

SELECT * FROM spin
            WHERE `serial` in (
            SELECT `serial` from spin group by `serial`
            HAVING count(*) > 1
            ) ORDER BY date ASC

    $query = $this->db->prepare($sql);
    $query->execute();
    return $query->fetchAll();

It works as expected but I want to filter this out to only show one of the values with its count of occurrences. I'm guessing it will need some sort of distinct adding to the query to get a unique value back but not sure how to implement this in the best way?

For anyone intrest this is how I'm returning the data (code shortened):

                        <thead>
                        <tr>
                            <th>Serial</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($spins as $spin) { ?>
                            <tr>
                                <td><?php if (isset($spin->serial)) echo $spin->serial; ?></td>
                                <td><?php if (isset($spin->test_started)) echo $spin->date; ?></td>
                            </tr>
                        <?php } ?>
                    </tbody>
1
  • Do you want to apply limit 1? Commented Dec 11, 2014 at 14:28

3 Answers 3

2

This query will do it:

SELECT *, COUNT(*) AS count
FROM spin
GROUP BY serial
HAVING count > 1
LIMIT 1
Sign up to request clarification or add additional context in comments.

Comments

0

To avoid nested select statements, use GROUP BY.

SELECT serial, COUNT(*) AS count FROM spin 
     GROUP BY serial HAVING count > 1 
     ORDER BY date ASC LIMIT 1;

Comments

0

Here are my assumptions, you want to return a list of serials that are repeated in your spin table, however, you only to show the repeated serial once. With your current query, you are fetching all the records in your spin table with duplicate serials.

The query below will return all the serials that have a count > 1, however, it will only show each serial once.

SELECT `serial`, COUNT(`serial`) AS serial_count, `date`
FROM `spin`
GROUP BY `serial`
HAVING serial_count > 1
ORDER BY `date` ASC;

If you want to see all the dates, try this:

SELECT `serial`, COUNT(`serial`) AS serial_count, GROUP_CONCAT(`date`) AS dates
FROM `spin`
GROUP BY `serial`
HAVING serial_count > 1
ORDER BY `date` ASC;

You could add a LIMIT at the end if you want to restrict the number of records your query returns.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.