笛卡尔加入MySQL查询

时间:2015-07-29 13:16:31

标签: mysql sql

假设我在表格中有以下数据:

'1','nid'
'1','step.nid'
'2','step.nid'
'3','step.nid'

这意味着每个nid可以有多个步骤,在这种情况下,对于nid = 1,我们有3个步骤。

如何编写查询以检索以下结果:

'1','nid'
'1','step.nid'
'1','nid'
'2','step.nid'
'1','nid'
'3','step.nid'

所以我需要将nid与每一步结合起来

2 个答案:

答案 0 :(得分:0)

不确定这正是您所期望的,但希望它对您有所帮助:

select *
from tbl t1
join tbl t2 on t1.str regexp t2.str and t1.id <> t2.id
;

答案 1 :(得分:0)

尝试:

select case o.type when 'nid' then n.column1 else s.column1 end output1,
       case o.type when 'nid' then n.column2 else s.column2 end output2
from yourTable n
cross join yourTable s
cross join (select 'nid' type union all select 'step') o
where n.column2='nid' and s.column2='step.nid'
order by n.column1, s.column1, o.type

SQLFiddle here