php / mysql - 使用union,如何根据选中的表设置变量?

时间:2013-03-20 13:21:09

标签: php mysql

使用下面的代码,我显示状态和注释,它可以按照需要工作,虽然我不完全理解我自己的代码..

我想实现以下目标:如果结果来自状态,$ link_type = status,如果结果来自评论,$ link_type = comment

这是我的尝试($ link_type现在总是'状态')

    $results = db_query("
    SELECT sid as ssid, created as screated, message as smessage, recipient as srecipient 
    FROM {statuses}
    WHERE created > :logout_stamp
    UNION
    SELECT sid as ssid, created as screated, comment as smessage, uid as srecipient 
    FROM {fbss_comments} fbss
    WHERE fbss.created > :logout_stamp
    ORDER BY screated DESC LIMIT 15", 
    array(':logout_stamp' => $logout_stamp))->fetchAll();

  // foreach the results
  foreach ($results as $result) {
      $user_status = user_load($result->srecipient);
      $user_comment = user_load($result->commentuid);
      $username_status = $user_status->name;
      $username_comment = $user_comment->name;
      $date_status = $result->screated;
      $date_comment = $result->commentcreated;

      if ($result->ccreated != NULL) {
        $link_type = "comment";
      }
      else {
        $link_type = "status";
      }

print '<a href="statuses/' . ($result->ssid) . '" class="notification_wrapper">' . '<b>' . $username_status . '</b>' . ' - ' . ($link_type) . ' - ' . strip_tags(substr($result->smessage,0,30)) . ' - ' . elapsed_time($date_status) . '</a>'; 

建议非常感谢

3 个答案:

答案 0 :(得分:1)

使用 st ,因为它返回1表示状态,2表示评论。

 SELECT 1 as st,sid as ssid, created as screated, message as smessage, recipient as srecipient 
    FROM {statuses}
    WHERE created > :logout_stamp
    UNION
    SELECT 2 as st sid as ssid, created as screated, comment as smessage, uid as srecipient 
    FROM {fbss_comments} fbss
    WHERE fbss.created > :logout_stamp
    ORDER BY screated DESC LIMIT 15

答案 1 :(得分:1)

将此值添加为额外字段:

 SELECT sid as ssid, created as screated, message as smessage, recipient as srecipient, "status" as link_type 
FROM {statuses}
WHERE created > :logout_stamp
UNION
SELECT sid as ssid, created as screated, comment as smessage, uid as srecipient,"comment" as link_type 
FROM {fbss_comments} fbss
WHERE fbss.created > :logout_stamp
ORDER BY screated DESC LIMIT 15

答案 2 :(得分:1)

您可以在查询中添加字段,如下所示:

$results = db_query("
    SELECT sid as ssid, created as screated, message as smessage, recipient as srecipient, 'status' as link_type
    FROM {statuses}
    WHERE created > :logout_stamp
    UNION
    SELECT sid as ssid, created as screated, comment as smessage, uid as srecipient, 'comment' as link_type
    FROM {fbss_comments} fbss
    WHERE fbss.created > :logout_stamp
    ORDER BY screated DESC LIMIT 15", 
    array(':logout_stamp' => $logout_stamp))->fetchAll();

现在在if条件中使用新字段:

$link_type = ($result->link_type == 'comment') ? "comment" : "status";