SQL从一列中获取顶部和底部元素,并将它们放在两个不同的列中

时间:2013-02-13 23:31:22

标签: sql select join

我有2个选择语句。我想从字母顺序中取出名字并将其放在标题为First的列中,并将其按字母顺序放在名为Last的列中的姓氏旁边。

SELECT Name AS 'First'
FROM contactlist
ORDER BY Name ASC
LIMIT 1;

SELECT Name AS 'Last'
FROM contactlist
ORDER BY Name DESC
LIMIT 1;

1 个答案:

答案 0 :(得分:0)

不确定为什么你需要这个,但是你去了:

SELECT First, Last
FROM (
  SELECT Name AS 'First'
  FROM contactlist
  ORDER BY Name ASC
  LIMIT 1
  ) t, (
  SELECT Name AS 'Last'
  FROM contactlist
  ORDER BY Name DESC
  LIMIT 1
  ) t2

获取所有名称并按行号(ASC First to DESC Last)匹配可能会更有趣 - 类似这样的事情:

SELECT First, Last
FROM (
  SELECT Name AS 'First',
    @rowNum:=@rowNum + 1 rn
  FROM contactlist
    JOIN (SELECT @rowNum:= 0) r
  ORDER BY Name ASC
  ) t JOIN
 (
  SELECT Name AS 'Last',
    @rowNum2:=@rowNum2 + 1 rn
  FROM contactlist
    JOIN (SELECT @rowNum2:= 0) r
  ORDER BY Name DESC
  ) t2 ON t.rn = t2.rn

还有一些Fiddle