简体   繁体   English

如何从表 doc_val 中获取每个 doc_id 表 doc_val 中最小“val”的行,其中标准 = 'L'

[英]How to get rows from table doc_val with minimum "val" from table doc_val for each of the doc_id where criteria = 'L'

You have two tables: 1. docs 2. doc_val你有两个表:1. docs 2. doc_val

Point of focus is table : doc_val , it has doc_id FK from table docs , field critera which will be our condition.重点是 table : doc_val ,它具有来自 table docs 的 doc_id FK ,字段标准将是我们的条件。

Mysql schema: Mysql 架构:

CREATE TABLE IF NOT EXISTS `docs` (
`id` int(6) unsigned NOT NULL,
`rev` int(3) unsigned NOT NULL,
`content` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `doc_val` (
`id` int(6) unsigned NOT NULL,
`doc_id` int(6) unsigned NOT NULL,
`val` int(3) unsigned NOT NULL,
`type` varchar(2) NOT NULL,
`criteria` varchar(2) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

INSERT INTO `docs` (`id`, `rev`, `content`) VALUES
('1', '1', 'The earth is flat'),
('2', '1', 'One hundred angels can dance on the head of a pin'),
('3', '1', 'The earth is flat and rests on a bull\'s horn'),
('4', '4', 'The earth is like a ball.');

INSERT INTO `doc_val` (`id`, `doc_id`, `val`, `type`, `criteria`) VALUES
('1', '1', 100, 'D', 'L'),
('2', '1', 101, 'D', 'L'),
('3', '1', 80, 'H', 'L'),
('4', '2', 10, 'H', 'S'),
('5', '2', 90, 'H', 'L'),
('6', '3', 100, 'D', 'L'),
('7', '3', 100, 'D', 'L');

expected output:预期输出:

在此处输入图片说明

DECLARE curIds CURSOR FOR SELECT DISTINCT doc_id FROM doc_val;
DECLARE id INT;
CREATE TEMPORARY TABLE temp(id int, doc_id int, val int, type char(1), criteria char(1));

OPEN curIds;

read_loop: LOOP
  FETCH curIds INTO id;
  INSERT INTO temp
   (Select * from doc_val 
    where val = (select min(val) 
                 from doc_val 
                 where doc_id = id)) AND criteria = 'L'

END LOOP;

SELECT * FROM temp;

Probably there is a syntax error but i hope you caught the idea.可能存在语法错误,但我希望你能理解这个想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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