UNION SUBSELECT 中的 MySQL 字段
我的数据库有以下表格:
- t1:博客文章
- t2:每个博客文章的附加表
- t3:博客文章的英语评论
- t4:博客文章的西班牙语评论
我有以下用例: 我需要获取每个博客文章的最新评论的 ID 以及博客文章本身。最新的评论可能位于 t3 或 t4 表中。
我想出了以下sql,但它没有按预期工作。
SELECT t1.id,
t1.one,
t1.two,
(
SELECT id FROM (
(SELECT * FROM t3 where t3.refid = t1.id)
UNION (SELECT * FROM t4 where t4.refid = t1.id)
ORDER BY datetime ASC LIMIT 1
) AS tempTable)
AS someValue
FROM t1
LEFT JOIN t2 ON (t1.id = t2.id)
WHERE t1.otherid=42 AND t1.somefield > 0
ORDER BY t1.someOtherField
LIMIT 5
任何有关是否和/或如何可能的提示都将受到高度赞赏,谢谢!
My database has the following tables:
- t1: blog posts
- t2: additional table for each blog post
- t3: english comments for blog posts
- t4: spanish comments for blog posts
And I have the following use case:
I need to fetch the id of the newest comment per blog post together with the blog post itself. The newest comment might be either in the t3 or t4 table.
I came up with the following sql, but it does not work as expected.
SELECT t1.id,
t1.one,
t1.two,
(
SELECT id FROM (
(SELECT * FROM t3 where t3.refid = t1.id)
UNION (SELECT * FROM t4 where t4.refid = t1.id)
ORDER BY datetime ASC LIMIT 1
) AS tempTable)
AS someValue
FROM t1
LEFT JOIN t2 ON (t1.id = t2.id)
WHERE t1.otherid=42 AND t1.somefield > 0
ORDER BY t1.someOtherField
LIMIT 5
Any hints on if and/or how this is possible are highly appreciated, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将包含 t3 和 t4 的最新评论的表编译到表
d
中然后将两个结果合并到注释表
c
中此
c
仅保存 1 个条目,即来自t3
或t4
的最新 ID,ct
将告诉您从哪个表获得响应;you need to compile a table with the most recent comments from t3 and t4 into table
d
then also combine the two results into comments table
c
this
c
would hold only 1 entry, the most recent id, either fromt3
, or fromt4
c.t
will tell you from which table you got the response;首先尝试这个查询,它应该返回 t3 和 t4 的最新评论 -
如果可以,那么让我们将此查询与 t1 表结合起来 -
Try this query firstly, it should return the latest comments from t3 and t4 -
If it OK, then let us combine this query with a t1 table -