【问题标题】:Mysql Nested/Multiple Query handlingMysql 嵌套/多查询处理
【发布时间】:2014-04-11 11:14:07
【问题描述】:

我有三个查询给了我单独正确的结果,但我的要求是我只需要一个查询的所有结果,所以我应该如何继续?

select * from user_post_like
inner join user_post  on user_post_like.postID = user_post.postID  
inner join Users on Users.userID=user_post_like.userID 
where (user_post.poster='$uid' AND user_post_like.userID!='$uid') 
ORDER BY likeID DESC;

select * from user_post_comment   
inner join user_post  on user_post_comment.postID = user_post.postID  
inner join Users on Users.userID=user_post_comment.commenter 
where (user_post.poster='$uid' AND  user_post_comment.commenter!='$uid') 
ORDER BY commentID DESC;

select * from user_post_share   
inner join user_post  on user_post_share.postID = user_post.postID  
inner join Users on Users.userID=user_post_share.Share_user_id 
where (user_post.poster='$uid' AND   user_post_share.Share_user_id!='$uid') 
ORDER BY shareID DESC;

【问题讨论】:

  • 我看到了一个与 user_post 的共同加入...也许这就是答案
  • @RobertRozas 可以吗,请提供查询?
  • @Datta 很好的评论。 Stack Overflow 的精髓。
  • 根据给出的信息,这三个查询似乎极其无关
  • @Ic 我有三个表,例如,comment,share,其中包含有关表 post 中的帖子的数据以及表 user 中的所有用户详细信息,因此我有三个单个查询工作正常,但是如何组合所有结果

标签: mysql database join


【解决方案1】:

由于您无论如何都要加入表格,因此您可以将所有列放在您的选择中 - 并保持您的语句可读。如果您有重复的列名(来自不同的表),您可能需要将它们与函数聚合并分组。

SELECT s.*, p.*, u.* 
FROM user_post_share s 
INNER JOIN user_post p ON s.postID = p.postID 
INNER JOIN Users u ON u.userID = p.poster 
WHERE (p.poster='$uid' AND s.Share_user_id != '$uid') 
ORDER BY shareID DESC 

【讨论】:

  • 感谢您的努力。但是这个查询只给我来自共享表的结果,而不是来自评论和喜欢表的结果,而不是来自那里的用户详细信息
  • 第一个错误,现已修复。
  • 新查询提供来自共享表的数据,而不是来自喜欢和评论表的数据
  • 我没有得到所有这些,但是我也不知道你的外键。您必须通过公共链接将它们全部连接在一起,并在连接和选择子句中为每个表使用不同的别名。
【解决方案2】:

试试这样的总结

select * from user_post_like,user_post_comment,user_post_share  <inner joins> <where conditions>

【讨论】:

  • 你可以在投票时发表评论吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 2020-05-17
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多