Unable to get unique values

I use my sql to get unique values ​​from the database

My query is as follows, but somehow I cannot get unique results

                    SELECT
            DISTINCT(company_name),
            sp_id               
        FROM
            Student_Training
        ORDER BY
            company_name

sp_id is the primary key, and then company_name is the name of the company, which must be unique.

as follows

sp_id, company_name
1      comp1
2      comp2
3      comp2
4      comp3

Just not sorting this unique

+3
source share
4 answers

DISTINCT will create unique rows, which means a unique combination of field values ​​in your query.

The following query will return a list of all unique company_names along with the first match for sp_id.

SELECT sp_id, company_name
FROM Student_Training
GROUP BY company_name

, , , MySQL DISTINCT(fieldname), DISTINCT(field1, field2, ..., fieldn)

+6

DISTINCT , , . (sp_id, company_name), .

, , , MySQL SELECT DISTINCT(company_name), sp_id, SELECT DISTINCT(company_name, sp_id). , .

Edit

, DISTINCT(company_name), sp_id : , : company_name (company_name) (((company_name))). , SQL: "DISTINCT [_ ], [sp_id]". , DISTINCT, , , , (AVG sp_id , , AVG(sp_id).)

SELECT DISTINCT company_name, (sp_id) SELECT DISTINCT (company_name), (sp_id), , . - (company_name, sp_id) - SQL, SELECT "" , ( , , . , ).

: - (

+7

id , company_name id?

:

SELECT  DISTINCT company_name                 
FROM    Student_Training

company_name.

:

SELECT  company_name, MIN(id)
FROM    Student_Training
GROUP BY
        company_name

id .

+3

DISTINCT does not work the way you think. This gives you a report. Stop and think about how he can return what you expect from him. If you had a table as follows

id    name
1     joe
2     joe
3     james

If it returns only single names, what id will return for joe?

You may want

SELECT company_name, Min(sp_id) FROM Student_Tracking GROUP BY company_name

or perhaps (as stated above) simply

SELECT DISTINCT company_name from student_training
+2
source

Source: https://habr.com/ru/post/1720887/


All Articles