tags:

views:

33

answers:

4

hi, there is a Q about MySQL

When i use this:

SELECT DISTINCT id FROM table

this works! but... when i want to filter only one column i try to do this:

SELECT DISTINCT prod_id, id, prod_picture FROM products

this gives me all table... i just need 1 picture for each product, like:

1 | 1 | asd.jpg
2 | 3 | weq.jph

not

1 | 1 | asd.jpg
1 | 2 | qwe.jpg
2 | 3 | weq.jpg

actually i try to use this:

SELECT DISTINCT 
  prod_list.id,
  prod_list.prodname,
  prod_pict.pict_file
FROM
  prod_list
  INNER JOIN urun_pict ON (prod_list.id = prod_pict_prod_id)

i have to filter just "prod_list.id"...

thanks

+2  A: 

use group by prod_id,

SELECT prod_id, id, prod_picture FROM products group by prod_id

work only if in run not with this sql_mode : ONLY_FULL_GROUP_BY , The default value is empty (no modes set).

Haim Evgi
The results of this query are undefined. You cannot include non-aggregate columns in a query with GROUP BY except those included in the GROUP BY clause.
Dan Grossman
see my update @dan, i use a lot of queries like that and its working
Haim Evgi
Just because it works does not mean it is correct, and doing something you know is incorrect means you're gambling that it'll continue to work if you upgrade the server or change configuration in the future. Better to do it right the first time. The MySQL manual specifically tells you the results of that query are undefined.
Dan Grossman
i dont hear about user that use this mode, and in the dafulat is not set,see this in the link http://dev.mysql.com/tech-resources/articles/debunking-group-by-myths.html Alas, MySQL's ONLY_FULL_GROUP_BY is not as clever as it should be, and there are particular cases where ONLY_FULL_GROUP_BY is too restrictive in enforcing only full GROUP BY clauses. The details are described here. The good news is that the community can help to fix this bug! Go to MySQL Forge and check out Worklog task 2489.
Haim Evgi
+2  A: 
SELECT prod_id, id, prod_picture
  FROM products
  GROUP BY prod_id
Ignacio Vazquez-Abrams
+3  A: 

You should GROUP BY the product id to collapse all rows for each id into one. All columns which are not part of your GROUP BY clause should be aggregate columns. You need to tell MySQL which of the possibly multiple values for the other columns you want. If you don't care, use MIN or MAX?

SELECT 
  prod_list.id, 
  prod_list.prodname,
  MAX(prod_pict.pict_file) AS `pict_file`,
FROM 
  prod_list
INNER JOIN
  prod_pict
ON
  prod_list.id = prod_pict.prod_id
GROUP BY
  prod_list.id,
  prod_list.prodname
Dan Grossman
awesome. thank you...
dreamlore
+1  A: 
SELECT
  prod_list.id,
  prod_list.prodname,
  prod_pict.pict_file
FROM
  prod_list
  INNER JOIN urun_pict ON (prod_list.id = prod_pict_prod_id)
GROUP BY prod_list.id

This should work.

MatTheCat
thank you very much.
dreamlore