2

I have a mysql query with a join and I want for each match to get one only row not all. What I mean.

for example we have the two tables

ids(int id)
colors(int id, varchar color)

I have the query

select ids.id, colors.color from ids join colors on ids.id = colors.id;

and get the following

id | color
------------------
1  | red 
1  | blue 
2  | yellow 
3  | green 
3  | pink

I want a query to get the

id | color 
-----------------
1  | red 
2  | yellow 
3  | green 

5 Answers 5

4

Try using a subquery which limits the amount of results:

select ids.id, (select colors.color WHERE colors.id = ids.id LIMIT 1) AS color FROM ids;
3
select 
  ids.id, 
  min(colors.color) as color
from 
  ids 
join 
  colors on ids.id = colors.id
group by
  ids.id
;
0

select ids.id, colors.color from ids join colors on ids.id = colors.id group by ids.id;

But remember: you get an unguaranteed value for colors.color.

2
  • On additional note, if Group By is applied here, what happens to non Numeric data type. It returns a random value? In numeric, we can obtain SUM, average etc. Aug 1, 2011 at 10:02
  • @shamim From documentation: The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Sorting of the result set occurs after values have been chosen, and ORDER BY does not affect which values the server chooses.
    – Vlad
    Aug 1, 2011 at 11:29
0
SELECT ids.id, colors.color FROM ids JOIN colors ON ids.id = colors.id GROUP BY ids.id
0

Thank you for your replies, all of you said me to use the group by Of course this method was the first that I tried, but I get the below error:

Column "COLORS.COLOR" must be in the GROUP BY list; SQL statement:

My query is the

SELECT 
    ids.id, colors.color 
FROM ids 
     JOIN colors ON ids.id = colors.id 
GROUP BY ids.id;

Also, I must say you that I use the h2database

Your Answer

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

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