mysql - 笛卡尔加入 MySQL 查询

标签 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

最佳答案

尝试:

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 .

关于mysql - 笛卡尔加入 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31701558/

相关文章:

sql - 如何使用 T-SQL 查询在 Active Directory 中获得大约 1000 条记录限制?

java - 在 mysql 查询中传递 java 字符串变量

php - 使用php删除sql数据库中的行

sql - 我可以在 'insert ... on duplicate update ...' 语句中重用绑定(bind)变量吗?

php - 从mysql中的另一个表获取数据

mysql - "Where IN"子句的 MariaDB 性能问题

sql - 可在 SQL Server 和 MS Access 中使用的 COALESCE、IFNULL 或 NZ() 函数

mysql - 通过 PHPmyadmin 导入 CSV 文件 : file not found or access denied

mysql - 为什么这个 SQL 查询不起作用?

php - 如何使用 ID 作为参数显示 SQL 数据库中的特定行