【问题标题】:MySQL - Select differentlyMySQL - 选择不同
【发布时间】:2012-09-17 10:41:40
【问题描述】:

我有这个查询,它为一列选择一个不同的值,但我还需要该查询中的其他内容。我需要它来获取与主选择关联的不同行。

让我举例说明...

这是我的查询:

$sql = 'SELECT DISTINCT user_id FROM ' . DONATION_SECURITY_TABLE;
$result = mysql_query($sql);

$rows = mysql_fetch_assoc($result);
mysql_free_result($result);

return $rows;

如您所见,它返回此查询返回 user_id 的 DISTINCT。

如果我在使用上述查询的返回创建的双 foreach 循环中使用这样的函数:

public function get_donor_status($user_id)
{
    global $db;

    $sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
           " WHERE user_id = '" . (int) $user_id . "'";
    $result = $db->sql_query($sql);

    $row = $db->sql_fetchrow($result);
    $payment_status = $row['payment_status'];

    $db->sql_freeresult($result);

    return $payment_status;
}

此函数将为 user_id 2 返回 Completed,但我希望它改为 Pending。如何更改我的查询,使其返回相应 user_id 的最后一个值?

如果我不够清楚,请告诉我,以便我重新解释。

【问题讨论】:

    标签: php mysql select


    【解决方案1】:

    只需选择用户的最后一行:

    "SELECT payment_status FROM " . DONATION_SECURITY_TABLE . " WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1"
    

    【讨论】:

      【解决方案2】:

      这个怎么样?

      $sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
                 " WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1";
      

      【讨论】:

        【解决方案3】:

        实际上可以在一条 SQL 语句中获取所有内容,无需双循环:

        SELECT
            user_id, payment_status
        FROM
            DONATION_SECURITY_TABLE t1
        WHERE
            donation_id = (select max(donation_id) from DONATION_SECURITY_TABLE t2 WHERE t2.user_id = t1.user_id)
        ORDER BY
            user_id
        

        【讨论】:

          猜你喜欢
          • 2011-11-07
          • 2016-05-03
          • 2013-03-20
          • 2016-11-13
          • 2017-03-25
          • 2021-02-14
          • 1970-01-01
          • 1970-01-01
          • 2020-10-14
          相关资源
          最近更新 更多