I have a schema that is setup as so:
Cards (card_id, fact_id, fact_view_id)
data_for_fact (fact_id, key, value)
Sample data:
[cards]: (51, 1, '2::1'), (52, 1, '2::2') ...
[data_for_fact]: (1, 'q', 'person'), (1, 'a', 'noun')
The intended output is:
[cards]: (51, 'person' (as q), 'noun' (as a)),
(52, 'noun' (as q), 'person' (as a))
With SQL Lite, how can I get the output that I'm looking for?
I've tried creating a join, but that only works on the first output card开发者_StackOverflow. The difference between the two cards are the fact_view id.
You could do it with a union:
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'
Or you could use CASE
expressions:
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'
精彩评论