0

如果我有一个类似的 mysql 查询

(SELECT COUNT(*) FROM data AS amount)
UNION
(SELECT COUNT(*) FROM data WHERE some < 50 AS something)

然后像这样用php创建一个数组$row = mysqli_fetch_array($sql, MYSQLI_ASSOC);

我现在如何处理每个 AS 名称。这不起作用:echo $row["amount"];. 我的第二个问题是为什么我不能AS something在有 WHERE 子句时使用?

4

4 回答 4

2

尝试这个:

(
  SELECT 
    'amount1' as za_name, 
    COUNT(*) as za_count 
  FROM 
    data
) 
UNION 
(
  SELECT 
    'amount2' as za_name, 
    COUNT(*) as za_count 
  FROM 
    data 
  WHERE some < 50 
)

然后你可以区分$row[za_name]并得到金额$row[za_count]

对于第二个问题:如果您制作临时表,则可以使用它:

SELECT
  tmp.za_name,
  tmp.za_count
FROM (
  SELECT 
    'amount2' as za_name, 
    COUNT(*) as za_count 
  FROM 
    data 
  WHERE some < 50 
) as tmp
于 2013-04-24T15:09:29.577 回答
1

UNION整个查询的行名称/别名中,无论它们在第一个查询中是什么。

所以如果你有

SELECT field1 AS A
UNION
SELECT field2 AS B

您的最终结果将只有一个A字段,该字段将同时包含field1field2

在您的查询中,您希望为 而COUNT(*)不是表起别名。

(SELECT COUNT(*) AS amount FROM data)
UNION
(SELECT COUNT(*) FROM data WHERE some < 50)

整个查询中的所有行也$row['amount']不会。COUNT(*)

于 2013-04-24T15:11:40.463 回答
0

在您的查询中

(SELECT COUNT(*) FROM data AS amount) UNION (SELECT COUNT(*) FROM data WHERE some < 50 AS something)

您将表别名为data名称amount而不是子查询

于 2013-04-24T15:08:18.060 回答
0

您必须以这种方式编辑查询(列上也有别名)

(SELECT COUNT(*) as amount FROM data)
UNION
(SELECT COUNT(*) as amount FROM data WHERE some < 50 AS something)

这样,您就可以$result['amount']通过 fetch assoc 方法进行寻址。

于 2013-04-24T15:09:57.317 回答