Mysql 如何使用2个字段进行查询?

Mysql 如何使用2个字段进行查询?,mysql,Mysql,我想在一个有4个字段的表中进行mysql查询:id、user\u one、user\u 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($ch

我想在一个有4个字段的表中进行mysql查询:id、user\u one、user\u 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语句不起作用。它总是伴随着其他部分。我的意思是,当我尝试运行它时,即使有超过1行,它也会在messages_组中随机创建一个新的散列。我该怎么办?

PHP区分大小写。应该是

if ($amsik['count(hash)'] > 0)
我建议您始终为计算字段指定别名,而不是使用公式作为键

SELECT COUNT(hash) AS hashcount ...
然后您可以使用
$amsik['hashcount']

代码中的另一个问题是:

$currenthash = $amsik['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)
。请看以下几件事:首先,如果您不确定事情发生的原因,请执行
var\u转储($amsik)包装在
标记中。更易于调试(您可以准确地看到
mysql\u fetch\u数组
查询返回的内容)。其次,
mysqli
函数已被弃用,请使用
mysqli
或类似工具。第三,您没有转义任何变量(至少在这个代码段中)。确保转义所有值。准备好的陈述有助于做到这一点。最后,请将您的
COUNT(hash)
列命名为更具体、更易于阅读的名称。Barmar,谢谢您的回答。我为facebook或任何网站等用户创建了一个对话部分。无论如何,它工作得很好,除非user1尝试向user2发送消息,否则每次都会创建新的对话。我希望它在第一次对话中插入新消息。如果这是第一次对话,那么创建一个新对话。是,查询返回散列计数,而不是任何特定的散列,但必须有1个散列最大值属于这2个特定用户(用户1和用户2)。如何将该散列作为当前散列?这是我在答案的第二部分中显示的内容。我编辑了我的答案,因为只有一行符合条件。从最初的问题来看,这并不明显。