0

我正在用 mysql 在 php 中做一个小游戏。现在我创建的一个 sql 查询有问题。这个想法是查询检查用户是否有足够的材料。

我有一个查询,如果我这样使用它,它会起作用:

SELECT
(
  SELECT COUNT(*)
  FROM building_requirements
  WHERE building_id = '1'
) as building_requirements_count,
(
  SELECT COUNT(*)
  FROM user_materials, building_requirements
  WHERE user_materials.material_id = building_requirements.material_id
    AND user_id = '27'
    AND building_id = '1'
    AND (user_material_amount >= building_material_amount) = 1
) as user_materials_count;

但是,当我添加一列使用这些子查询的结果时,它会失败:

SELECT
(
  SELECT COUNT(*)
  FROM building_requirements
  WHERE building_id = '1'
) as building_requirements_count,
(
  SELECT COUNT(*)
  FROM user_materials, building_requirements
  WHERE user_materials.material_id = building_requirements.material_id
    AND user_id = '27'
    AND building_id = '1'
    AND (user_material_amount >= building_material_amount) = 1
) as user_materials_count, 
building_requirements_count = user_materials_count as enough_materials;

我得到错误:

#1054 - Unknown column 'building_requirements_count' in 'field list'

有人可以向我解释为什么我不能在这里使用子查询的结果吗?我该如何解决这个问题?

4

2 回答 2

1

你在哪里

building_requirements_count = user_materials_count as enough_materials;

我想你可能是说...

building_requirements_count - user_materials_count as enough_materials;
于 2010-07-12T10:24:11.880 回答
0

因为在您的表定义中没有名为“building_requirements_count”的字段。此处不允许使用自定义字段,WHERE 部分除外。

为什么不在查询的 WHERE 部分使用自定义字段?

编辑: 将每个值从数据库中分离出来并在 PHP 中进行计算会更容易。

$result = mysql_query("SELECT COUNT(*) FROM building_requirements WHERE building_id = '1'");
if ($result) {
  $row = mysql_fetch_row($result);
  $building_requirements_count  = $row[0];
}
else {
  $building_requirements_count = 0;
}

$query = "  SELECT COUNT(*)
  FROM user_materials, building_requirements
  WHERE user_materials.material_id = building_requirements.material_id
    AND user_id = '27'
    AND building_id = '1'
    AND (user_material_amount >= building_material_amount) = 1";

$result2 = mysql_query($query);
if ($result2) {

  $row = mysql_fetch_row($result2);
  $user_material_count  = $row[0];
}
else {
  $user_material_count = 0;
}

$enough_materials = ( $user_material_count >= $building_requirements_count) ? true : false;
于 2010-07-12T10:21:34.463 回答