如何查询2个字段?

时间:2015-12-12 01:27:31

标签: mysql

我想在一个包含4个字段的表中进行mysql查询:id,user_one,user_two,hash。

   $check_con = mysql_query("SELECT count(hash) FROM messages_group WHERE (user_one=$my_id AND user_two=$other_id) OR (user_one=$other_id AND user_two=$my_id)");

    $amsik = mysql_fetch_array($check_con);
        $currenthash=$amsik['hash'];

           if ($amsik['COUNT(hash)'] > 0){
            mysql_query("INSERT INTO messages VALUES('', '$currenthash', '$my_id', '$message')");
            header('location: m.php?hash='.$currenthash.'');
           } else{
           mysql_query("INSERT INTO messages_group VALUES('$my_id', '$other_id', '$random_number','')");
           mysql_query("INSERT INTO messages VALUES('', '$random_number', '$my_id', '$message')");
           header('location: m.php?hash='.$random_number.'');
           }
       } 

此if语句不起作用。它总是与else部分一起使用。我的意思是当我尝试运行它时,即使有超过1行,它也会在messages_group中通过随机数创建一个新的哈希。我该怎么办?

1 个答案:

答案 0 :(得分:0)

PHP区分大小写。它应该是

if ($amsik['count(hash)'] > 0)

我建议您始终为计算字段指定别名,而不是将公式用作键。

SELECT COUNT(hash) AS hashcount ...

然后您可以使用$amsik['hashcount']

代码中的另一个问题是:

$currenthash = $amsik['hash'];

查询不会返回hash列。您可以使用MAX(hash)返回当前哈希值:

SELECT COUNT(hash) AS hashcount, MAX(hash) AS hash ...

或者你可以这样做:

SELECT hash
FROM messages_group
WHERE (user_one=$my_id AND user_two=$other_id) OR (user_one=$other_id AND user_two=$my_id)
LIMIT 1

然后你可以这样做:

$amsik = mysql_fetch_assoc($check_con);
if ($amsik) {
    $currenthash = $amsik['hash'];
    mysql_query("INSERT INTO messages VALUES('', '$currenthash', '$my_id', '$message')");
header('location: m.php?hash='.$currenthash.'');
} else{
   mysql_query("INSERT INTO messages_group VALUES('$my_id', '$other_id', '$random_number','')");
   mysql_query("INSERT INTO messages VALUES('', '$random_number', '$my_id', '$message')");
   header('location: m.php?hash='.$random_number.'');
}

顺便说一句,除非hash可以NULL,并且您需要在计算时跳过这些,否则您应该使用COUNT(*)而不是COUNT(hash)。见count(*) and count(column_name), what's the diff?