到目前为止,我在搜索组合4个表时没有成功。我有4张桌子:
内容
content_id | source_id | content_title | content_date
--------------------------------------------------------
1 | 1 | The factory | 189982398300
2 | 2 | Cold and cloudy | 189982398299
3 | 2 | Green tea | 189982398298
来源
source_id | source_name
-------------------
1 | BBC
2 | Reuters
设置
setting_id | setting_name
-------------------------------
1 | bbc_iplayer_string
2 | reuters_video_id
3 | reuters_category
content_join_settings
content_id | setting_id | setting_data
------------------------------------------
1 | 1 | Js88sdhjsd0gDS09
2 | 2 | video_8AJK3ADJD8
2 | 3 | weather
3 | 2 | video_K7KD8N2ND9
3 | 3 | food and drinks
因为您可能已经注意到每个内容记录都有自己的源链接,并根据源提供额外的设置。 BBC帖子有bbc_iplayer_string
,路透社的帖子有reuters_video_id
和reuters_category
。当然这只是一个例子。
我希望将结果合并,并将setting_name
作为列名。我不确定如何解释它所以我会展示它:
content_id | source_name | content_title | content_date | bbc_iplayer_string | reuters_video_id | reuters_category
--------------------------------------------------------------------------------------------------------
1 | BBC | The factory | 189982398300 | Js88sdhjsd0gDS09 | NULL | NULL
2 | Reuters | Cold and cloudy | 189982398299 | NULL | video_8AJK3ADJD8 | weather
3 | Reuters | Green tea | 189982398298 | NULL | video_K7KD8N2ND9 | food and drinks
我对复杂的MySQL查询不是很熟练。我不知道从哪里开始寻找,更不用说搜索什么了。我从这个查询开始,但我不知道如何继续。我可能不是很亲密。
SELECT
*
FROM
content,
sources,
settings,
content_join_settings
WHERE
content.content_id = content_join_settings.content_id AND
settings.setting_id = content_join_settings.setting_id AND
sources.source_id = content.source_id
GROUP BY
content.content_id
ORDER BY
content.content_date
DESC
答案 0 :(得分:3)
您需要加入表格,然后转动结果以将行移动到列中。
SELECT c.content_id, s.source_name, c.content_title, c.content_date,
MAX(CASE setting_name WHEN 'bbc_iplayer_string' THEN setting_data END) AS bbc_iplayer_string,
MAX(CASE setting_name WHEN 'reuters_video_id' THEN setting_data END) AS reuters_video_id,
MAX(CASE setting_name WHEN 'reuters_category' THEN setting_data END) AS reuters_category
FROM content AS c
INNER JOIN sources AS s ON s.source_id = c.source_id
INNER JOIN content_join_settings AS cjs ON cjs.content_id = c.content_id
INNER JOIN settings as st ON st.setting_id = cjs.setting_id
GROUP BY c.content_id
答案 1 :(得分:-2)
这会有帮助吗?
SELECT
*
FROM
content as ct inner join sources as ss on ct.source_id = ss.source_id
inner join content_join_settings as cst on ct.setting_id = cst.setting_id
inner join settings as st on st.setting_id = cst.setting_id
GROUP BY
content.content_id
ORDER BY
content.content_date
DESC