Only get a repeated value in mysql

Asked

Viewed 1,200 times

2

Guys, I have a table and in it a field called cargo and what value it can repeat, as for example, the teaching position. In my HTML I’m riding a <select> When I recover the value of this field, only due to its repeated value it shows several times the word teacher or any other that will be repeated in the table, logical. I wonder if there is some way to "filter" and extract only one value from these repeated?

  • 2

    The solution would be to normalize this table, a table for positions and another for employees, the field cargo(description) is not in the employees table, only your id(id_cargo). PLEASE DON’T USE DISTINCT.

  • @rray why can’t I use the DISTINCT?

  • 2

    It doesn’t solve the problem, it just masks it. Have you ever wondered what happens when the last intern is promoted or fired? this position will still be available in the combo? Edit the question and put the structure of this table.

  • The ideal would be to segment in 2 tables, as rray commented. A table where the position data will be and another one with the employee data, and an employee should contain a position...

2 answers

1


There are two methods:

1. Would be using DISTINCT

SELECT DISTINCT(cargo) FROM tabela

2. It would be using GROUP BY:

SELECT cargo FROM tabela GROUP BY cargo

Test this clicking here!

Both methods have the same result, as can be visualized, there is not much to explain. The Group By is to group by equal, summarizing will display one of the duplicates, so it will no longer be a duplicate. = D

  • I didn’t understand why the down votes...

  • Neither. I actually thought it was something I had put (see editions) but anyway. At least the author of the publication approved and apparently served.

  • 1

    It was explained that, in this case, distinct is not the best option. The best option is to normalize the table! Work with Foreign Keys, distinct in this case, is gambiarra! The first comment made on the question, shows how it should be done.

-1

SELECT cargo FROM `tabela` GROUP BY `tabela`.`cargo` =`cargo`;

In this way, I force the results where my field is equal to the field that I intend to bring only one result, but the ideal is to use normalization as previously said.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.