【问题标题】:MYSQL : Mix data from 3 tables and JOIN with another tableMYSQL:混合来自 3 个表的数据并与另一个表连接
【发布时间】:2014-05-24 20:32:00
【问题描述】:

我已经搜索了很长时间,以在 stackoverflow 和 google 上找到一个看起来像我的查询,但还没有找到我想要的。也尝试了很多查询,但我对 SQL 不够熟练:(

Posts (id, title, url)
Imgs (id, title, url)
Zaps (id, title, url)

Comments(id, T_id, date, user, comment, from)

T_id = ids from Posts, Imgs, Zaps

from = contain text from wich table the data come from ("post", "img", "zap")

表 Comments 包含 3 个表中的所有混合 cmets。 我正在尝试获得此输出:

Comments.id, Comments.user, Comments.comment, Comments.from, title, url

最后一个 cmets 的列表以及它所来自的表的标题和 url。

我知道我的架构有点搞砸了,它正在生产中,我无法真正改变它。

如果有人可以帮助我,我将不胜感激。

谢谢!

【问题讨论】:

  • 你说的最后的cmets是什么意思?您是否只需要每个表的一个或 n 个最近的 cmets?
  • 如果您为每个表发布一组示例行和所需输出的示例,这可能会有所帮助,但我想我理解我之前的问题。
  • 你能解释一下表格的列吗?它们是如何归属的?
  • 最后的 cmets,无论他们来自哪张桌子。但是,@Chad 的响应似乎有效,我在查询末尾添加了 order by 和 limit,它返回了我所期望的。
  • @Jens 就像我说的那样,我的架构并没有真正优化或任何东西,但是看看 Chad 给出的响应和它使用的连接,这是链接它们的正确方法。

标签: mysql join union


【解决方案1】:

您需要将 cmets 中的 T_id/from 列与右表中正确的唯一 id 匹配。

select c.id, c.user, c.comment, c.from, t.title, t.url
from Comments c, Posts t
where c.T_id=t.id and c.from='post'
union
select c.id, c.user, c.comment, c.from, t.title, t.url
from Comments c, Imgs t
where c.T_id=t.id and c.from='img'
union
select c.id, c.user, c.comment, c.from, t.title, t.url
from Comments c, Zaps t
where c.T_id=t.id and c.from='zap'

【讨论】:

  • UNION ALL 集合运算符通常比 UNION 具有更好的性能,因为它避免了识别要从结果集中删除的重复项的额外步骤。
  • 我不知道为什么......我离这个查询不远,但我设法失败了......这个查询有效,但我用“左连接”替换了旧的连接,一切都很好,谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 2016-04-29
  • 2011-08-29
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多