简体   繁体   English

如何获取MySQL定义的名称成PHP?

[英]How to get in MySQL defined names into php?

If I have a mysql query like 如果我有一个像mysql这样的查询

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

and then create an array with php like this $row = mysqli_fetch_array($sql, MYSQLI_ASSOC); 然后用php创建一个数组,像这样$row = mysqli_fetch_array($sql, MYSQLI_ASSOC); .

How can I now address each of the AS names. 现在如何解决每个AS名称。 This does not work: echo $row["amount"]; 这不起作用: echo $row["amount"]; . The second question I have is why can't I use AS something when having a WHERE clause? 我的第二个问题是为什么拥有WHERE子句时为什么不能使用AS something

Try this: 尝试这个:

(
  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 
)

Then you can differentiate by $row[za_name] and get the amount $row[za_count] 然后,您可以通过$row[za_name]并获得金额$row[za_count]

For the second question : you can use it if you make a temp table : 对于第二个问题:如果创建临时表,则可以使用它:

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

In a UNION the row names/aliases for the entire query are whatever they are in the first query. UNION中,整个查询的行名/别名与第一个查询中的行名/别名相同。

So if you have 所以如果你有

SELECT field1 AS A
UNION
SELECT field2 AS B

Your final result will only have an A field, which will have both field1 and field2 . 您的最终结果将只有一个A字段,该字段将同时具有field1field2

In your query, you want to alias the COUNT(*) , not the table. 在查询中,您要为COUNT(*)而不是表加上别名。

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

Nor $row['amount'] will be all of the COUNT(*) rows from the entire query. $row['amount']也不是整个查询中的所有COUNT(*)行。

in your query 在您的查询中

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

You are aliasing the table data to the name amount rather than the sub-query 您将表data别名为名称amount而不是子查询的别名

You have to edit the query this way (aliases on the columns, too) 您必须以这种方式编辑查询(在列上也使用别名)

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

This way You are able to address $result['amount'] as a result from the fetch assoc method. 这样,您就可以通过获取assoc方法处理$result['amount']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM