如何组合复杂的数据

时间:2011-02-17 01:35:45

标签: sql database sqlite

我有一个设置如下的架构:

Cards         (card_id, fact_id, fact_view_id)
data_for_fact (fact_id, key, value)

示例数据:

  [cards]:  (51, 1, '2::1'), (52, 1, '2::2') ...
  [data_for_fact]: (1, 'q', 'person'), (1, 'a', 'noun')

预期输出为:

 [cards]: (51, 'person' (as q), 'noun' (as a)), 
          (52, 'noun' (as q), 'person' (as a))

使用SQL Lite,我如何获得我正在寻找的输出?

我尝试过创建连接,但这只适用于第一张输出卡。两张牌之间的区别是fact_view id。

1 个答案:

答案 0 :(得分:1)

你可以用联盟来做:

SELECT card_id, ques.value AS q, ans.value AS a
    FROM cards
    JOIN data_for_fact AS ques 
      ON cards.fact_id=ques.fact_id AND ques.key='q'
    JOIN data_for_fact AS ans 
      ON cards.fact_id=ans.fact_id AND ans.key='a'
    WHERE cards.fact_view_id='2::1'
UNION ALL
SELECT card_id, ans.value AS q, ques.value AS a
  FROM cards
    JOIN data_for_fact AS ans 
      ON cards.fact_id=ans.fact_id AND ans.key='a'
    JOIN data_for_fact AS ques 
      ON cards.fact_id=ques.fact_id AND ques.key='q'
  WHERE cards.fact_view_id='2::2'

或者你可以使用CASE表达式:

SELECT card_id, 
       CASE cards.fact_view_id WHEN '2::1' THEN ques.value ELSE  ans.value END AS q, 
       CASE cards.fact_view_id WHEN '2::1' THEN  ans.value ELSE ques.value END AS a 
  FROM cards
    JOIN data_for_fact AS ques 
      ON cards.fact_id=ques.fact_id AND ques.key='q'
    JOIN data_for_fact AS ans 
      ON cards.fact_id=ans.fact_id AND ans.key='a'