Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql select distinct

I am trying to select of the duplicate rows in mysql table it's working fine for me but the problem is that it is not letting me select all the fields in that query , just letting me select the field name i used as distinct , lemme write the query for better understading

mysql_query("SELECT DISTINCT ticket_id FROM temp_tickets ORDER BY ticket_id")  mysql_query("SELECT * , DISTINCT ticket_id FROM temp_tickets ORDER BY ticket_id") 

1st one is working fine

now when i am trying to select all fields i am ending up with errors

i am trying to select the latest of the duplicates let say ticket_id 127 is 3 times on row id 7,8,9 so i want to select it once with the latest entry that would be 9 in this case and this applies on all the rest of the ticket_id's

Any idea thanks

like image 751
Shanon Avatar asked Aug 30 '11 22:08

Shanon


People also ask

How do I SELECT distinct data in MySQL?

To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.

Does MySQL have distinct?

Description. The MySQL DISTINCT clause is used to remove duplicates from the result set. The DISTINCT clause can only be used with SELECT statements.

How do I SELECT one column as distinct?

Adding the DISTINCT keyword to a SELECT query causes it to return only unique values for the specified column list so that duplicate rows are removed from the result set.


2 Answers

DISTINCT is not a function that applies only to some columns. It's a query modifier that applies to all columns in the select-list.

That is, DISTINCT reduces rows only if all columns are identical to the columns of another row.

DISTINCT must follow immediately after SELECT (along with other query modifiers, like SQL_CALC_FOUND_ROWS). Then following the query modifiers, you can list columns.

  • RIGHT: SELECT DISTINCT foo, ticket_id FROM table...

    Output a row for each distinct pairing of values across ticket_id and foo.

  • WRONG: SELECT foo, DISTINCT ticket_id FROM table...

    If there are three distinct values of ticket_id, would this return only three rows? What if there are six distinct values of foo? Which three values of the six possible values of foo should be output?
    It's ambiguous as written.

like image 154
Bill Karwin Avatar answered Oct 02 '22 12:10

Bill Karwin


Are you looking for "SELECT * FROM temp_tickets GROUP BY ticket_id ORDER BY ticket_id ?

UPDATE

SELECT t.*  FROM  (SELECT ticket_id, MAX(id) as id FROM temp_tickets GROUP BY ticket_id) a   INNER JOIN temp_tickets t ON (t.id = a.id) 
like image 40
a1ex07 Avatar answered Oct 02 '22 12:10

a1ex07