SQL命令-两个不同的表有一个相同的键。

时间:2021-08-09 08:14:47

I have two tables:

我有两个表:

Table A:  ID Items Data Pos
Table B:  ID Apples Oranges Pos

And what I need to get all results from Table A and B ordered by position. How can I do this? SELECT * FROM Table a and b orderby pos?

我需要从表A和B的位置得到所有结果。我该怎么做呢?从表a和b orderby pos中选择* ?

So for example the result should look like this:

例如,结果应该是这样的:

  1. Result from Table A with Id 1 Items 10 Data 5 and Pos 1
  2. 由表A和Id 1项目10数据5和Pos 1。
  3. Result from Table B with Id 1 Apples 3 Oranges 3 and Pos 2
  4. 结果由表B和Id 1苹果3和2。
  5. Result from Table B with Id 2 Items 4 Data 4 and Pos 3
  6. 由表B和Id 2项目4数据4和Pos 3的结果。
  7. Result from Table A with Id 2 Apples 7 Oranges 8 and Pos 4
  8. 结果由表A和Id 2苹果7橙8和Pos 4。

Thank you.

谢谢你!

1 个解决方案

#1


2  

You would use union all with an order by:

你将会使用一个order by:

select ID, Items, Data, Pos
from tableA a
union all
select ID, Apples, Oranges, Pos
from tableB b
order by Pos

This is standard SQL so it will work in all the databases you mention.

这是标准的SQL,所以它将在您提到的所有数据库中工作。

#1


2  

You would use union all with an order by:

你将会使用一个order by:

select ID, Items, Data, Pos
from tableA a
union all
select ID, Apples, Oranges, Pos
from tableB b
order by Pos

This is standard SQL so it will work in all the databases you mention.

这是标准的SQL,所以它将在您提到的所有数据库中工作。