使用PostgreSQL我有两个查询。我想结合两个查询来返回两个用逗号分隔的整数值。
SELECT * from newlayerya_1 ORDER BY id DESC LIMIT 1
SELECT * from newlayerya_1 ORDER BY id ASC LIMIT 1
- 应该返回例如141,23
我尝试了一些我在网上找到的例子,但对此并不高兴。
CREATE FUNCTION test_ret(a integer, b integer) RETURNS RECORD AS $$
DECLARE
ret RECORD;
BEGIN
-- Arbitrary expression to change the first parameter
--IF LENGTH(a) < LENGTH(b) THEN
-- SELECT TRUE, a || b, 'a shorter than b' INTO ret;
SELECT * from newlayerya_1 ORDER BY id DESC LIMIT 1 INTO ret;
-- ELSE
-- SELECT FALSE, b || a INTO ret;
SELECT * from newlayerya_1 ORDER BY id ASC LIMIT 1 INTO ret;
--END IF;
RETURN ret;
END;$$ LANGUAGE plpgsql;
答案 0 :(得分:2)
试试这个
SELECT id from newlayerya_1 ORDER BY id DESC LIMIT 1
UNION
SELECT id from newlayerya_1 ORDER BY id ASC LIMIT 1
请记住,两个查询的字段数应相同。
答案 1 :(得分:1)
SELECT
(SELECT id from newlayerya_1 ORDER BY id DESC LIMIT 1),
(SELECT id from newlayerya_1 ORDER BY id ASC LIMIT 1)
应避免任何反模式,例如将整数转换为字符串。
或者,甚至更简单...
SELECT
MAX(ID), MIN(ID)
FROM
newlayera_1
答案 2 :(得分:0)
UNION关键字执行此操作;只要两个查询都返回相同的列(您的那些列)。
答案 3 :(得分:0)
SELECT row_number() OVER (ORDER BY id ASC) as rnum1,
row_number() OVER (ORDER BY id DESC) as rnum2
from newlayerya_1
where STUFF = 'STUFF'
limit 1
答案 4 :(得分:0)
SELECT *
FROM yourdatabase
WHERE ID = (SELECT MAX(ID) FROM yourdatabase) or
ID = (SELECT MIN(ID) FROM yourdatabase);