我有一个声明,根据链接表基于共享标签和扬声器的数量对项目进行排名,但我希望它能够从主tbl_talks中提取talk_title和talk_brief信息,而这些信息实际上不在查询中现在(只使用链接表)。 基本上,链接表有talk_id和tag_id或talk_id和speaker_id。
我尝试了几种尝试LEFT JOIN的方法,或者在应用了union的配对SELECT中添加tbl_talks但没有运气。我需要将tbl_linking_talk_tag.talk_id和tbl_linking_speakers_talk与tbl_talks.talk_id相关联,然后从tbl_talks获取talk_title和talk_brief
SELECT talk_id, count(*) AS common_term_count FROM
(
SELECT talk_id FROM tbl_linking_talk_tag WHERE tag_id IN
(SELECT tag_id FROM tbl_linking_talk_tag WHERE talk_id = 1)
UNION ALL
SELECT talk_id FROM tbl_linking_speakers_talk WHERE speaker_id IN
(SELECT speaker_id FROM tbl_linking_speakers_talk WHERE talk_id = 1)
) AS accumulator_table
WHERE talk_id != 1
GROUP BY talk_id
ORDER BY common_term_count DESC
答案 0 :(得分:1)
在这种情况下,不要认为你需要一个工会。如果你需要的只是数数,那么为什么不试试像......
SELECT talk_id, (SELECT count(*)FROM tbl_linking_talk_tag sub WHERE tag_id IN (SELECT tag_id FROM tbl_linking_talk_tag WHERE talk_id = 1)和maintalk.talk_id = sub.talk_id)+ (SELECT count(*)FROM tbl_linking_speakers_talk sub1 WHERE speaker_id IN (SELECT speaker_id FROM tbl_linking_speakers_talk WHERE talk_id = 1)和maintalk.talk_id = sub1.talk_id ),talk_title,talk_brief 来自maintalk 其中talk_id!= 1 按talk_id分组
语法可能需要一些修复,但方法是
从维护
中选择列答案 1 :(得分:0)
我使用了这段代码:
SELECT a.talk_id, a.talk_image, a.talk_title, a.talk_brief, count(b.talk_id) AS common_term_count
FROM tbl_talks a LEFT OUTER JOIN
(
SELECT talk_id FROM tbl_linking_talk_tag WHERE tag_id IN
(SELECT tag_id FROM tbl_linking_talk_tag WHERE talk_id = 1)
UNION ALL
SELECT talk_id FROM tbl_linking_speakers_talk WHERE speaker_id IN
(SELECT speaker_id FROM tbl_linking_speakers_talk WHERE talk_id = 1)
) AS b
ON a.talk_id = b.talk_id
WHERE a.talk_id != 1
GROUP BY b.talk_id
ORDER BY common_term_count DESC