2013-02-13 31 views
1

我有两个表:从两个表中选择 - 通过排序结果外国和主键

  1. 科:_id,名
  2. 项目:_id,名称,SECTION_ID

我试图以这样的方式排序结果:

1 Section1 
1 Item1 1 
2 Item2 1 
3 Item3 1 
2 Section2 
4 Item4 2 
5 Item5 2 

换句话说 - 将属于该部分的项目放在该部分本身之下。

是否可以使用一个查询来实现这样的结果?

编辑

现在我使用INNER JOIN,但它不是完全适合我的目的:我想知道里面查询不同部分的确切数量,这将是巨大的,如果我能要知道(现在我只是通过section_id排序和寻找它的变化)

+0

你打算展示你试过的吗? – Jodrell 2013-02-13 17:13:10

+0

你是否想要显示额外的数字,如果是的话,它们来自哪里? – Jodrell 2013-02-13 17:15:13

+1

这是可能的,但我通常不认为这是一个好主意。为什么你想纯粹用SQL来完成? – 2013-02-13 17:16:00

回答

3

像这也许下一节的确切位置,here is some fiddle

select 
     s._id sid, 
     s.name, 
     null iid 
    from 
     section s 
union all 
select 
     i.section_id sid, 
     i.name, 
     i._id iid 
    from 
     item i 
    order by 
     sid, iid 
2

它可以像

select section._id as sectionId,section.name, 0 as itemId 
from section 
union 
select item.section_id as sectionId, item.name, item._id as itemId 
from item 
order by sectionId, itemId 
+1

Works,http://sqlfiddle.com/#!5/5c1d4/10 – 2013-02-13 17:45:51

相关问题