2

I'm trying to find duplicates and select the result with the least value combination in a table.

Until now I'm only able to select the result that has the lowest value on a column using MIN(). I thought it would be easy to just replace MIN with LEAST and change the columns.

Here's a layout:

 CREATE TABLE `index`.`products` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(10) NOT NULL , `price` INT NOT NULL , `availability` INT NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;

INSERT INTO `products` (`id`, `name`, `price`, `availability`) VALUES 
(NULL, 'teste', '10', '1'),
(NULL, 'teste', '5', '2'),
(NULL, 'teste', '3', '3');

The simplified layout

id - name - price - availabilty
1  - test - 10 - 1
2  - test - 5 - 2  
3  - test - 3 - 3

using the following query:

select name, MIN(price) from products group by name having count(*) > 1

gets me the lowest price. I'm trying to get the lowest price and lowest availabilty.

select name, LEAST(price, availability) from products group by name having count(*) > 1

This doesn't work.

Clarification: I want to select the row with the lowest price and lowest availabity. In this case it should be the first one I guess.

I should clarifity that 1=available, 2=not available and 3=coming soon

Strawberry
  • 33,750
  • 13
  • 40
  • 57
xnny
  • 41
  • 6

1 Answers1

0

The statement to select lowest price for the best availability is:

set sql_mode=only_full_group_by;
SELECT 
    name, MIN(price), availability
FROM
    products
JOIN
    (
        SELECT 
            name, MIN(availability) availability
        FROM
            products
        GROUP BY name
    ) as x
USING (name , availability)
GROUP BY name , availability;
woocash
  • 36
  • 4
  • The duplicate is the name column. All 3 rows have the same name. – xnny Feb 07 '17 at 20:15
  • I'm getting the same error as a previous answer: #1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'index.products.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by – xnny Feb 07 '17 at 20:33
  • Ok! Almost there. This works if I remove the id from the 3rd SELECT. Otherwise it gives me the same error. I think I can work with this now. But do you think it's possible to have the id there? – xnny Feb 07 '17 at 20:53
  • I didn't testing it before with `only_full_group_by` now should be ok – woocash Feb 07 '17 at 20:57
  • Thank you @woocash. Unfortunately I don't have the id. However this works just fine! Thank you – xnny Feb 07 '17 at 21:03