开发者

MySQL returning multiple rows as columns

开发者 https://www.devze.com 2023-03-28 01:29 出处:网络
I\'m a bit rusty with SQL, I have one simple table col1col2col3col4 ident1name1data1data3 ident2name1data8data7

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-lin开发者_运维技巧e 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?


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).

select col1 from table -> iterate through result adding two copies of each to 
                          keys of an associative array

select col1, col2, col3, col4 from table -> output name. while name = first
                                            name output col3 then col4

Your other option, near as I can tell, actually should be done in dynamic sql (using the PREPARE statement and the like).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号