MySQL 返回多行作为列
我对 SQL 有点生疏,我有一个简单的表
col1 col2 col3 col4
ident1 name1 data1 data3
ident2 name1 data8 data7
ident3 name1 data3 data8
...
ident1 name2 data4 data1
ident2 name2 data2 data5
ident3 name2 data6 data3
...
,我想以这种方式获取几列
ident1 ident1 ident2 ident2 ident3 ident3 ...
name1 data1 data3 data8 data7 ...
name2 data4 data1 data2 data5 ...
name3 ....
...
请注意,这与 MySQL:从内联子查询返回多列,因为我只有一个表,并且我想将第一列映射为第一行在 结果。
我已经读过,这对于像 SELECT ... WHERE (col3,col4) IN (SELECT col3, col4 ...) 这样的子查询是可能的,但我遇到了类似 Unknown column col3 in 'IN/ALL/ANY subquery' 的错误我不知道如何获取结果中第一行的列名称以及如何使用分组来添加列。有什么帮助吗?
I'm a bit rusty with SQL, I have one simple table
col1 col2 col3 col4
ident1 name1 data1 data3
ident2 name1 data8 data7
ident3 name1 data3 data8
...
ident1 name2 data4 data1
ident2 name2 data2 data5
ident3 name2 data6 data3
...
and I want to get several columns in this way
ident1 ident1 ident2 ident2 ident3 ident3 ...
name1 data1 data3 data8 data7 ...
name2 data4 data1 data2 data5 ...
name3 ....
...
Note this is not the same as MySQL: Returning multiple columns from an in-line subquery since I have just one table and I want to map the first column as the first row in the results.
I've read this is possible with subqueries like SELECT ... WHERE (col3,col4) IN (SELECT col3, col4 ...), but I'm gettin error like Unknown column col3 in 'IN/ALL/ANY subquery' and I can't figure out how to get the column names in the first row in the results and how to use group by to add columns. Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来像 mdx。那些太棒了。但这不是那些。但它们之所以存在,是因为
SQL
(各种变体)在这方面不好。 (这也可能是您需要重新考虑架构的情况)。亲自?我会将其作为一系列查询和关联数组来完成(伪代码如下)。
据我所知,您的另一个选择实际上应该在动态 sql 中完成(使用 PREPARE 语句等)。
Looks like mdx. Those are awesome. But this isn't those. But they exist because
SQL
(in all varieties) is just bad at this. (This may also be a case where you need to re-think your schema).Personally? I would do this as a series of queries and associative arrays (pseudocode follows).
Your other option, near as I can tell, actually should be done in dynamic sql (using the
PREPARE
statement and the like).