基于字段值,MySQL如何连接不同的表?

4
我可以帮助您翻译以下内容,这是关于编程的:

我有一个包含网站上最新评论的表格,并且我想根据评论类型加入不同的表格。

评论表格的结构类似于:

id | type | ressource_id |
---+------+--------------+
1  |  1   |      10      |
2  |  3   |       7      |

我想做的是如果类型为type = 1,则加入“新闻”表(on news.id = comments.ressource_id),如果类型为type = 3,则加入“教程”表等等。
请问我该如何实现?我尝试使用CASEUNION进行不同的查询,但从未得到预期的结果。
谢谢。
2个回答

6
尝试使用“左外连接”和“on”子句匹配“type”:
select coalesce(n.id, t.id) id
,      c.type
,      c.resource_id
from   comments c
left
outer
join   news n
on     n.id = comments.resource_id
and    c.type = 1
left
outer
join   tutorial t
on     t.id = comments.resource_id
and    c.type = 3

非常感谢您的快速回答,它完美地解决了我的问题!我之前也尝试过使用 coalesce,但是忘记了使用 OUTER JOIN,现在我明白了。 - SuN
1
只是来这里说声谢谢,通过谷歌搜索找到了这个,正好可以根据ID更改数据 :) - NaughtySquid

2

您可以使用联合查询来实现此操作,假设您可以将部分查询强制转换为产生类似的模式,例如:

select n.id as id, c.something as something
    from news n, comments c
    where n.type = 1
    and   n.id = c.resource_id
union all
select n.id as id, t.something as something
    from news n, tutorial t
    where n.type = 3
    and   n.id = t.resource_id

换句话说,第一个查询仅将newscomments连接到news.type指示评论的行,第二个查询将newstutorials连接到news.type指示教程的行。然后,联合操作将两者合并为单个记录集。
在这种情况下(以及许多其他情况),我建议避免使用case语句,因为它几乎总是需要对数据进行逐行修改,而这很少能够良好扩展。运行两个查询并组合结果通常更有效率。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接