views:

665

answers:

2

Currently I have this query:

SELECT column1,column2 FROM table

column1 needs to be distinct, column2 does not.

SELECT DISTINCT column1, NON-DISTINCT column2 FROM table

Now I know that doesn't make sense but I need column1 to be distinct and column2 to be anything. How would I do that.

+1  A: 

Try this (fastest):

SELECT *
FROM `table`
GROUP BY pid
HAVING min( id )

second (slower) option:

select *
from `table` t1
where
    t1.id = (select min(id) from `table` t2 where t1.pid = t2.pid)
martin.malek
:( isn't there a way to do it without the "group/min"?
John
Why don't you want the grouping? SELECT DISTINCT is for getting unique values only, other values you try and select will be ambiguous. Should it select 2 or 7 as the bla1?
DisgruntledGoat
There is no way how to do that without group, or there is - subselect, but this will be slow. Or you can delete these records if you don't want them. Why you don't want to use group by?
martin.malek
goat -> i want to do this (select pid,bla1 from table) but i only want pid to be distinct // malek -> because i think there is an easier way to do it.
John
without group by, but not easier :-) I think you will not find easier way:select *from test t1where t1.id = (select min(id) from test t2 where t1.pid = t2.pid)
martin.malek
well if i do "select distinct pid,bla1 from table" does distinct apply to pid, bla1 or both?
John
Actually, since he's using MySQL and if the value of bla1 doesn't really matter he could simply use `SELECT pid, bla1 FROM table GROUP BY pid`. Note that this SQL isn't portable, and will only work on MySQL (most - if not all - other RDBMSs will complain about the use of GROUP BY without aggregate functions).
wimvds
+2  A: 
select pid, group_concat(distinct bla1) as bla1s
from table
group by pid;

The above will get you 1 row for each pid and you'll be able to see if there are extra bla1s without introducing a new column or having to settle for a random choice of multiple bla1s.

dnagirl