在另一列中选择MIN(column)的最有效方法

时间:2019-02-04 15:57:52

标签: mysql syntax greatest-n-per-group

基于此数据:

create table wp_posts (
  ID integer primary key auto_increment,
  post_title varchar(30),
  post_type varchar(30)
);

create table wp_postmeta (
  ID integer primary key auto_increment,
  post_id integer,
  meta_key varchar(30) not null default '_regular_price',
  meta_value integer not null
);

insert into wp_posts (post_title, post_type) values
('Apple Pie','Product'),
('French Toast','Product'),
('Shepards Pie','Product'),
('Jam Pie','Product'),
('Jam Pie','Product'),
('Plate','Not a Product'),
('Bucket','Not a Product'),
('Chequebook','Not a Product'),
('French Toast','Product'),
('French Toast','Product'),
('Banana','Product'),
('Banana','Product'),
('Banana','Product');

insert into wp_postmeta (post_id, meta_value) values
(1,10),
(2,5),
(3,9),
(4,8),
(5,11),
(6,12),
(7,10),
(8,6),
(9,1),
(10,1),
(11,2),
(12,1),
(13,7);

此SQL查询

SELECT wp_posts.post_title, MIN(wp_postmeta.meta_value)                            
FROM   wp_postmeta 
JOIN wp_posts ON wp_postmeta.post_id = wp_posts.id 
WHERE  wp_posts.post_type = 'Product' 
  AND wp_postmeta.meta_key = '_regular_price' 
GROUP BY wp_posts.post_title

会给予

+--------------+-----------------------------+
|  post_title  | MIN(wp_postmeta.meta_value) |
+--------------+-----------------------------+
| Apple Pie    |                          10 |
| French Toast |                           1 |
| Shepards Pie |                           9 |
| Jam Pie      |                           8 |
| Banana       |                           1 |
+--------------+-----------------------------+

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=fa38dd4e21395ad3855cf880a65afc2a

但是,我还希望另一列wp_posts.post_id(唯一)的行中具有相应的值。如何将其有效地包含在SELECT中?

2 个答案:

答案 0 :(得分:2)

使用row_number()窗口函数

select ID,post_title,post_type,meta_value from 
(SELECT wp_postmeta.ID,post_title,post_type ,meta_value,
row_number()over(partition by post_title order by wp_postmeta.meta_value) rn                           
FROM   wp_postmeta 
JOIN wp_posts ON wp_postmeta.post_id = wp_posts.id 
WHERE  wp_posts.post_type = 'Product' 
  AND wp_postmeta.meta_key = '_regular_price' 

) t where t.rn=1

答案 1 :(得分:0)

您可以使用MAX(wp_posts.id)

SELECT MAX(wp_posts.id) AS post_id, wp_posts.post_title, MIN(wp_postmeta.meta_value)                            
FROM   wp_postmeta 
JOIN wp_posts ON wp_postmeta.post_id = wp_posts.id 
WHERE  wp_posts.post_type = 'Product' 
  AND wp_postmeta.meta_key = '_regular_price' 
GROUP BY wp_posts.post_title
post_id | post_title   | MIN(wp_postmeta.meta_value)
------: | :----------- | --------------------------:
      1 | Apple Pie    |                          10
     10 | French Toast |                           1
      3 | Shepards Pie |                           9
      5 | Jam Pie      |                           8
     13 | Banana       |                           1