How can I write an SQL (MYSQL Database) statement that will return a result set which is unique in conjunction with two columns?
To make my question as simple as possible, let's say I have only two tables images
and products
. I want to query all the images of a certain set of products that have the string Swatch
in the the field, images
. This query succeeds with the following SQL using a MYSQL database:
SELECT
images.alt,
images.product_id,
images.src
FROM
images
INNER JOIN products
ON products.product_id IN (
"2112055640177",
"2112056590449",
"2112055378033",
"2112062292081",
"2112058490993",
"2112062619761",
"2112062488689",
"2112066420849",
"2112061833329",
"2112052527217"
)
WHERE
images.alt LIKE "%Swatch%";
However the result set is full of duplicates:
Black Tuscan - Swatch 2112049971313 foobar.com
Black Tuscan - Swatch 2112049971313 foobar.com
Black Tuscan - Swatch 2112049971313 foobar.com
Generic Black - Swatch 2112049971313 baz.com
Generic Black - Swatch 2112049971313 baz.com
Florence - Swatch 2112049971313 foobaz.com
Florence - Swatch 2112049971313 foobaz.com
Gold - Swatch 2112050593905 bazfoo.com
Gold - Swatch 2112050593905 bazfoo.com
Sand - Swatch 2112050593905 bazfoo.com
Sand - Swatch 2112050593905 bazfoo.com
Every product id set of images has duplicates (example: Black Tuscan - Swatch 2112049971313 foobar.com
, Black Tuscan - Swatch 2112049971313 foobar.com
)
I would like the result set to not contain duplicate product swatches . In other words, images should be unique by images.alt and images.product_id. Ideally instead of the above return value the result set should the following:
Black Tuscan - Swatch 2112049971313 foobar.com
Generic Black - Swatch 2112049971313 baz.com
Florence - Swatch 2112049971313 foobaz.com
Gold - Swatch 2112050593905 bazfoo.com
Sand - Swatch 2112050593905 bazfoo.com
Black Tuscan - Swatch 1234586923813 foobar.com
Sand - Swatch 1234586923813 bazfoo.com
Notice how for each product id there are no duplicate alt text values.
I have done a lot of searching and I have found these SO posts (one, two, and three). They have suggested combinations of SQL that use either a LEFT JOIN
, or GROUP BY
, or DISTINCT
but I have not been able to find the correct SQL statement that gets me the uniqueness I am looking for - unique by images.alt and images.product_id.