php - 显示多个mysql表的结果并排序

标签 php mysql sorting

我有 4 张 table :

Table 1: Users
    id
    username

Table 2: Acts
    act_id
    act
    user_id
    act_score
    act_date

Table 3: Votes
    vote_id
    act_id
    user_voter_id
    score_given
    date_voted

Table 4: Comments
    comment_id
    comment
    commenter_id
    act_commented
    date_commented

我想根据用户 ID 显示 Acts VotesComments 的内容,并组合在按日期顺序排序的列表中。与 Facebook 的 NewsFeed 类似的想法。

示例输出:

05-02-2014 10:00 Comment: "That's funny"
04-02-2014 12:30 Act Posted: "This is what I did"
04-02-2014 11:00 Comment: "Rubbish"
03-02-2014 21:00 Comment: "Looks green to me"
02-02-2014 09:00 Voted: +10 "Beat my personal best" by Cindy
01-02-2014 14:25 Act Posted: "Finally finished this darn website!"

我尝试沿着创建VIEW路线将所有必需的信息添加到表中,但是 这是错误的道路。现在我不知道该怎么办!

最佳答案

使用UNION组合单独的查询。例如,要获取三个表中的 10 个最新事件:

(
  -- my acts
  SELECT   a.act_date timestamp,
           'Act Posted' type,
           a.act description,
           u.username
  FROM     Acts a
      JOIN Users u ON u.id = a.user_id
  WHERE    a.user_id = ?
  ORDER BY a.act_date DESC
  LIMIT    10

) UNION ALL (

  -- votes on my acts
  SELECT   v.date_voted,
           CONCAT('Voted ', v.score_given),
           a.act,
           u.username
  FROM     Votes v
      JOIN Acts a USING (act_id)
      JOIN Users u ON u.id = v.user_voter_id
  WHERE    a.user_id = ?
  ORDER BY v.date_voted DESC
  LIMIT    10

) UNION ALL (

  -- comments on my acts
  SELECT   c.date_commented,
           'Comment',
           c.comment,
           u.username
  FROM     Comments c
      JOIN Acts a ON a.act_id = c.act_commented
      JOIN Users u ON u.id = c.commenter_id
  WHERE    a.user_id = ?
  ORDER BY c.date_commented DESC
  LIMIT    10
)
ORDER BY timestamp DESC
LIMIT    10

关于php - 显示多个mysql表的结果并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22194795/

相关文章:

php - 找不到 Symfony 3 方法 'guessExtension()' 和 'move()'

php - php和mysql注册系统

php - 在 Laravel 页面上从 MySQL 填充数据

php - XML SOAP 保存到 mySQL 数据库

带有日期范围分析的 MYSQL 交叉表 : days as rows, sum as columns

algorithm - 按词典顺序生成排列与排序?

php - 在1个查询mysql中插入多行

php - 获取 JSON 数据

php - 使用 while 从查询中排序信息?

algorithm - shell脚本排序列表