[英]Get more info from a MAX(ID), MIN(ID) MYSQL query?
How to get more columns from MAX(ID), MIN(ID)
MYSQL query? 如何从
MAX(ID), MIN(ID)
MYSQL查询中获取更多列?
Currently I get only two values: MAX(ID) & MIN(ID)
from this query: 目前我只得到两个值:来自此查询的
MAX(ID) & MIN(ID)
:
SELECT MIN(ID), MAX(ID) FROM mytable WHERE mytable.series = 'white' ;
Need to get something like this-pseudo-query: 需要得到像这样的伪查询:
SELECT column1, column2
FROM mytable
WHERE series = 'white'
AND ID=Max(ID)
'AND GET ME ALSO'
WHERE series = 'white'
AND ID=Min(ID);`
It should return 2 rows for the column 'series' that equals 'white'. 对于“系列”列,它应返回2行,等于“白色”。
1st with column1 and column2 for ID=Min(ID). 第1列为column1,第2列为ID = Min(ID)。 2nd with column1 and column2 for ID=Max(ID).
第2列为column1,第2列为ID = Max(ID)。
But how? 但是怎么样?
Here is an approach using UNION
: 这是一种使用
UNION
的方法:
SELECT column1, column2
FROM mytable
WHERE series = 'white' AND ID IN
(
SELECT MIN(ID) FROM mytable WHERE series = 'white'
UNION
SELECT MAX(ID) FROM mytable WHERE series = 'white'
)
For good performance add a combined index on (series, id)
. 为了获得良好的性能,请在
(series, id)
上添加组合索引。
Or another variation which may have better performance: 或者可能具有更好性能的另一种变体:
(
SELECT column1, column2
FROM mytable
WHERE series = 'white'
ORDER BY ID
LIMIT 1
)
UNION
(
SELECT column1, column2
FROM mytable
WHERE series = 'white'
ORDER BY ID DESC
LIMIT 1
)
This will also be able to use the combined index on (series, id)
. 这也可以在
(series, id)
上使用组合索引。
A simpler solution: 更简单的解决方案:
SELECT a.column1, a.column2
FROM mytable a
JOIN (
SELECT MIN(ID) AS minid, MAX(ID) AS maxid
FROM mytable
WHERE series = 'white'
) b ON a.ID IN (b.minid, b.maxid)
It's exactly as you say: 就像你说的那样:
SELECT
column1, column2
FROM
mytable as m,
(SELECT MIN(ID) as mid, MAX(ID) as xid
FROM mytable WHERE mytable.series = 'white'
) t
WHERE
m.ID = t.mid or m.ID = t.xid;
The select in parentheses is the inner select that you can use just like another table. 括号中的select是内部选择,您可以像使用另一个表一样使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.