显示多个mysql表和排序的结果

时间:2014-03-05 10:18:05

标签: php mysql sorting

我有4张桌子:

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!"

我尝试沿着create VIEW路线向下添加所有必需的信息但是 这是错误的道路。现在我不知道该怎么做!

2 个答案:

答案 0 :(得分:2)

使用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

答案 1 :(得分:-1)

首先将id作为外键,并在3个表的其余部分中使用它,同时将数据插入到这3个表中。

与Acts表类似,表结构应如下所示。

Table 2: Acts
    id  //this is user id which is stored in the session while login.
    act_id
    act
    user_id
    act_score
    act_date

另一件事是在他/她登录时管理每个用户的会话。 将user_id存储在会话中以供进一步使用,如下所示。

session_start();
$_SESSION['user_id']=$_POST['ID'];

然后,为特定表格选择查询。我给出了选择查询的示例。

$sql="select * from Acts where id='".$_SESSION['id']."' ORDER BY act_date DESC";
$query=mysql_query($sql) or die("query failed");

现在,您将按日期获得特定用户订单的行为结果。然后在任意位置打印。