paste(1) in SQL

扶醉桌前 提交于 2019-12-24 07:44:59

问题


How in SQL could you "zip" together records in separate tables (à la the UNIX paste(1) utility)?

For example, assuming two tables, A and B, like so:

   A          B
========    ====
Harkness    unu
Costello    du
Sato        tri
Harper
Jones

How could you produce a single result set

   NAME  | NUM
===============
Harkness | unu
Costello | du
Sato     | tri
Harper   | NULL
Jones    | NULL

?


回答1:


In SQL Server 2005, Oracle 9i and PostgreSQL 8.4 and higher:

SELECT  name, num
FROM    (
        SELECT  name, ROW_NUMBER() OVER (ORDER BY id) AS rn
        FROM    a
        ) qa
LEFT JOIN
        (
        SELECT  num, ROW_NUMBER() OVER (ORDER BY id) AS rn
        FROM    b
        ) qb
ON      qb.rn = qa.rn
ORDER BY
        qa.rn

Note that ROW_NUMBER() requires that the records are explicitly sorted.

If you don't have a column similar to id, you cannot sort the records in order other than alphabetical, since relational databases have no concept of implicit record order.




回答2:


Without some identifying information to associate rows in one to another you shouldn't. Order or records in SQL should not matter, now if you altered your table to be like.

 ID | NAME
===============
1 | Harkness
2 | Costello
3 | Sato 
4 | Harper
5 | Jones

ID | Num
=========
 1| uno
2 | du
3 | tri

Then a simple

SELECT * FROM A LEFT JOIN B ON A.ID=B.ID;


来源:https://stackoverflow.com/questions/2676138/paste1-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!