[英]MySQL query to select SUM of longtext data type and store result as variable
I need to select some values from a table column which has a datatype of "longtext" where another column has a specific value and add those values up. 我需要从具有“ longtext”数据类型的表列中选择一些值,其中另一列具有特定值,然后将这些值加起来。 I need to store the sum as a variable which I will a.) echo on a webpage, and b.) use the value in a calculation later in the page.
我需要将总和存储为变量,我将a。)在网页上回显,并且b。)在页面稍后的计算中使用该值。
This works to find all of the values which I need to add up: 这可以找到我需要累加的所有值:
$query = "SELECT meta_value
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'
ORDER BY CAST(`meta_value` AS UNSIGNED) DESC";
and I can display the results with: 我可以通过以下方式显示结果:
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row['meta_value']. "<br>";
}
From my searching, I think I am close with my query, but my page fails to load when I try to echo the results. 从我的搜索中,我认为我已经接近查询了,但是当我尝试回显结果时,页面无法加载。 Here is what doesn't work:
这是行不通的:
$query = "SELECT CAST(SUM('meta_value') as UNSIGNED)
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row[SUM('meta_value')]. "<br>";
}
As you may have guessed, this is a Wordpress database table, and I cannot change the datatype. 您可能已经猜到,这是一个Wordpress数据库表,我无法更改数据类型。 As always, your help is appreciated!
一如既往地感谢您的帮助!
EDIT - Trying Gordon Linoff's suggestion below, I have removed the single quotes around meta_value. 编辑-在下面尝试Gordon Linoff的建议,我删除了meta_value周围的单引号。 It still doesn't work, but thank you for the suggestion:
它仍然不起作用,但是谢谢您的建议:
$query = "SELECT CAST(SUM(meta_value) as UNSIGNED)
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row[SUM(meta_value)]. "<br>";
}
SOLVED: 解决了:
Thank you to Gordon Linoff for pointing out my typographical error. 感谢Gordon Linoff指出我的印刷错误。 I ended up making a sample table and hammering this out on my own.
我最终制作了一个样本表,并亲自完成了这个工作。 Indeed, the single quotes in my query were not needed.
确实,我的查询中不需要单引号。 However, where I was echoing the results, I needed the single quotes, but they were in the wrong place.
但是,在我回显结果的地方,我需要单引号,但它们的位置错误。 Note
$row['SUM(meta_value)']
instead of $row[SUM('meta_value')]
. 注意
$row['SUM(meta_value)']
而不是$row[SUM('meta_value')]
。
Additionally, I did not need to use CAST (which didn't work), because MYSQL will by default treat values as mathematical values if the query uses math. 另外,我不需要使用CAST(该方法无效),因为如果查询使用数学,则默认情况下,MYSQL将把值视为数学值。
$query = "SELECT meta_key, SUM(meta_value)
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row['SUM(meta_value)'] ."<br>";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.