开发者

Flattening SQL tables into single CSV-friendly table

I'm taking over a database that needs to be presented in aCSV-friendly format for certain reasons.

Currently three tables exists. One with basic descriptions of an object, e.g.:

id | date       | name
1  | 2008-10-10 | Maestro
2  | 2008-10-12 | Domo

Then I have another table containing event types and descriptions:

ev_id | desc   | desc2
1     | Event1 | "Something less good happened"
2     | Event2 | "Something good happened"

Finally a third table making a connection between the two:

id | 开发者_运维知识库ev_id
1  | 2
2  | 1

What I need is to combine the three, such that each row in the event table produces a column in the final view together with the original object descriptions. If an event has occurred, a 1 should be inserted in the corresponding cell, otherwise 0 or NULL. E.g.:

id | date       | name    | Event1 | Event2
1  | 2008-10-10 | Maestro | 0      | 1
2  | 2008-10-12 | Domo    | 1      | 0

Is this possible using SQL (MySQL)?


SELECT A.*,
       (CASE WHEN B.ev_id = 1 THEN 1 ELSE 0 END) EVENT_1,
       (CASE WHEN B.ev_id = 2 THEN 1 ELSE 0 END) EVENT_2,
       .........
       .........
       (CASE WHEN B.ev_id = N THEN 1 ELSE 0 END) EVENT_N,
FROM   table1 A JOIN table2 B
ON     A.id = B.id

The only way to do this in mysql is to construct the query dynamicially by looping through the number of events in the events master table and then adding the same number of columns to the above query using dynamic sql and then execute.

SET @S = ' <construct the query> like the sample above ';
PREPARE n_StrSQL FROM @S;
EXECUTE n_StrSQL;
DEALLOCATE PREPARE n_StrSQL;

hope this helps

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜