简体   繁体   中英

MySQL - Select value only once based on another field

My database schema is like following:

CREATE TABLE test (
  id INT(11) UNSIGNED PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  priority ENUM('low', 'medium', 'high') NOT NULL
);

INSERT INTO test (id, title, priority) VALUES (1, 'test', 'medium');
INSERT INTO test (id, title, priority) VALUES (2, 'test', 'high');
INSERT INTO test (id, title, priority) VALUES (3, 'test2', 'low');

And my query is like following:

SELECT * FROM test 
ORDER BY FIELD(priority, 'high', 'medium', 'low');

I would like to do a DISTINCT on field title based on priority field. For example, if there are two or more data with the same title , I would like to select only the one with the highest priority, so in my case the expected results would be the data with id 2 and 3. How to do it?

One method is:

SELECT t.*
FROM test t
WHERE FIELD(priority, 'high', 'medium', 'low') =
          (SELECT MIN(FIELD(priority, 'high', 'medium', 'low'))
           FROM test t2
           WHERE t2.title = t.title
          );

EDIT:

I didn't think that priorities could be repeated. The above can be modified to use the id :

SELECT t.*
FROM test t
WHERE id = (SELECT id
            FROM test t2
            WHERE t2.title = t.title
            ORDER BY FIELD(priority, 'high', 'medium', 'low')
            LIMIT 1
           );

Try this...

Table and sample data

CREATE TABLE test (
  id INT(11) UNSIGNED PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  priority ENUM('low', 'medium', 'high') NOT NULL
);

INSERT INTO test (id, title, priority) VALUES (1, 'test', 'medium');
INSERT INTO test (id, title, priority) VALUES (2, 'test', 'high');
INSERT INTO test (id, title, priority) VALUES (3, 'test2', 'low');
INSERT INTO test (id, title, priority) VALUES (4, 'test2', 'low');
INSERT INTO test (id, title, priority) VALUES (5, 'test2', 'low');
INSERT INTO test (id, title, priority) VALUES (6, 'test', 'low');
INSERT INTO test (id, title, priority) VALUES (7, 'test3', 'low');
INSERT INTO test (id, title, priority) VALUES (8, 'test3', 'high');
INSERT INTO test (id, title, priority) VALUES (9, 'test3', 'medium');

Query

SELECT Max(t2.id)  AS ID,
       t1.title    AS Title,
       t1.priority AS Priority
FROM   (SELECT title,
               Min(priority) AS priority
        FROM   test
        GROUP  BY title
        ORDER  BY Field(priority, 'high', 'medium', 'low')) t1
       INNER JOIN test t2 using (title, priority)
GROUP  BY t1.title,
          t1.priority;  

Output

+-----+--------+----------+
| ID  | Title  | Priority |
+-----+--------+----------+
|  2  | test   | high     |
|  5  | test2  | low      |
|  8  | test3  | high     |
+-----+--------+----------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM