MySQL-根据其他字段仅选择一次值

时间:2019-03-20 16:53:41

标签: mysql sql

我的数据库架构如下:

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');

我的查询如下:

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

我想基于DISTINCT字段在字段title上进行priority。例如,如果有两个或多个具有相同title的数据,我只想选择一个优先级最高的数据,因此在我的情况下,预期结果将是ID为2和3的数据。要做吗?

2 个答案:

答案 0 :(得分:0)

一种方法是:

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
          );

编辑:

我不认为可以重复优先次序。可以将以上内容修改为使用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
           );

答案 1 :(得分:0)

尝试一下...

表和样本数据

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');

查询

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;  

输出

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