Sum value of all rows of a column with multiple tables - php

Im using this to get a total count
$exe = mysql_query('SELECT SUM(field_3) FROM t_a');
$res = mysql_fetch_row($exe);
echo 'Total Count: ' .$res[0] . ' / XX';
But I need it from multiple tables with the same structure, named t_a, t_b, all the way to t_z

You can use Union All in my sql
select sum(field_3) total
from
(
select field_3
from t_a
union all
select field_3
from t_b
) t
group by field_3

Related

PHP/SQL how can I combine 2 requests into one

so i have 1 query it makes possible combine 2 rating numbers into one
SELECT (SELECT SUM(rating) FROM " . PREFIX . "_post_extras WHERE user_id ='{$row['user_id']}') + (SELECT SUM(rating) FROM " . PREFIX . "_comments WHERE user_id ='{$row['user_id']}') AS rating
how do I change my query so that the rating that is in the postextras and in the postcomments was one as in the first request? and to sort by the common rating?
this is my query that i cant to change: there doesnt have rating from table _comments but i need it too.
SELECT dle_users.user_id, dle_users.user_group, dle_users.name, dle_users.foto, SUM(dle_post_extras.rating) as rating
FROM dle_users
JOIN dle_post_extras ON dle_post_extras.user_id = dle_users.user_id
WHERE dle_post_extras.rating > '0'
GROUP BY dle_users.user_id
ORDER BY dle_post_extras.rating
DESC LIMIT 0,10

Single query to get all the table name, row count and count of rows where status is '1' in a given database

I am trying to get the table name, number of records in each table and number of records in each table with status='2' in a given database, and display the result through jtable plugin. I tried query something like
$sql = "SELECT TABLE_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' and TABLE_SCHEMA = '{$table_schema}' ORDER BY " . $_GET["jtSorting"] . " LIMIT " . $_GET["jtStartIndex"] . "," . $_GET["jtPageSize"] . ";";
TABLE_ROWS returns approx value, how to get exact value and how to get count of record with status=2 in same query.
Thanks,
Samir
I think you will require to write a procedure which can return you custom row counts for each table. Below is query which can give you list of tables with total row count, but if you would to have row count based on filter(i.e. status=2) , than you will require to write a procedure where you can have a loop and get row counts for each table based on your filters.
SELECT SCHEMA_NAME(A.schema_id) + '.' +
A.Name as tablename, SUM(B.rows) AS 'RowCount'
FROM sys.objects A
INNER JOIN sys.partitions B ON A.object_id = B.object_id
WHERE A.type = 'U'
GROUP BY A.schema_id, A.Name
Thanks
Suresh

Getting the values of a MySQL enum using only SQL

In a web application, I need to populate a <select> with all possible values of a MySQL enum.
When I execute either of:
SHOW COLUMNS FROM mytable LIKE 'mycolumn';
SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'mytable' AND COLUMN_NAME = 'mycolumn';
I always end up with enum('valueA','valueB','valueC').
I know I can parse it with PHP but can it be done using SQL only?
I need something like this:
+-----------------+
| values |
+-----------------+
| valueA |
| valueB |
| valueC |
+-----------------+
This is one of Chris Komlenic's 8 Reasons Why MySQL's ENUM Data Type Is Evil:
4. Getting a list of distinct ENUM members is a pain.
A very common need is to populate a select-box or drop down list with possible values from the database. Like this:
Select color:
[ select box ]
If these values are stored in a reference table named 'colors', all you need is: SELECT * FROM colors ...which can then be parsed out to dynamically generate the drop down list. You can add or change the colors in the reference table, and your sexy order forms will automatically be updated. Awesome.
Now consider the evil ENUM: how do you extract the member list? You could query the ENUM column in your table for DISTINCT values but that will only return values that are actually used and present in the table, not necessarily all possible values. You can query INFORMATION_SCHEMA and parse them out of the query result with a scripting language, but that's unnecessarily complicated. In fact, I don't know of any elegant, purely SQL way to extract the member list of an ENUM column.
While I would agree about not using enums most of the time, it is possible in a single SQL statement:-
SELECT DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING(COLUMN_TYPE, 7, LENGTH(COLUMN_TYPE) - 8), "','", 1 + units.i + tens.i * 10) , "','", -1)
FROM INFORMATION_SCHEMA.COLUMNS
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
WHERE TABLE_NAME = 'mytable'
AND COLUMN_NAME = 'mycolumn'
This will work for enums with up to 100 possible values
This is the simplest solution
$EnumColum = $mysqli->query(
$link,
"SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'mrb_shipping_carriers' AND COLUMN_NAME = 'uspsServiceType'"
) or die("Error in " . ": " . __FILE__ . ": " . __LINE__);
$replace1 = preg_replace("/enum/", '',$EnumColum[0]['COLUMN_TYPE']);
$replace2 = preg_replace("/\(/", '',$replace1);
$replace3 = preg_replace("/\)/", '',$replace2);
$replace4 = preg_replace("/\'/", '',$replace3);
$newArray = explode(',',$replace4);
foreach($newArray as $value){
echo $value . "\n<br>";
}

Returning Mysql result with COUNT( * )

I'm trying to return a count from mysql. My code is below
$number_of_options_sql = tep_db_query("SELECT COUNT( * ) FROM
(select sum(options_id) as total from products_attributes
where products_id='".$products_id."' group by options_id) as total");
$number_of_options_result = tep_db_fetch_array($number_of_options_sql);
When I run this query in Phpmyadmin, it shows the result with COUNT(*) at the table heading. I'm getting the correct result, the query works for me, I just can't print it out on the screen.
I've tried returning the value the following ways and neither print anything on the screen:
echo $number_of_options_result[COUNT( * )];
echo $number_of_options_result[total];
Use AS field_name after COUNT(*)
$number_of_options_sql = tep_db_query("SELECT COUNT(*) AS field_name FROM (select sum(options_id) as total from products_attributes where products_id='".$products_id."' group by options_id) as total");
To print:
echo $number_of_options_result['field_name'];
(Replace "field_name" with any relevant name of your choice)
Your query is assigning an alias to the table/query not the column. use this one below:
$number_of_options_sql = tep_db_query("SELECT COUNT(*) as total FROM (select sum(options_id) as total from products_attributes where products_id='".$products_id."' group by options_id) a");
$number_of_options_result = tep_db_fetch_array($number_of_options_sql);
Also looks like you want to know count of distinct options id for a product_id, I would rewrite the query as follows:
$number_of_options_sql = tep_db_query("SELECT COUNT(DISTINCT options_id) as total FROM products_attributes WHERE products_id='".$products_id."'");
Just edit your query to
SELECT COUNT(*) as count FROM ....
then it will be stored like 'count' and you can print it the $number_of_options_result[count]; way.
put in a variable "total"
$number_of_options_sql = tep_db_query("SELECT COUNT(*) as total
then it works
echo $number_of_options_result['total'];

MySQL UNION with COUNT aliasing

I am trying to retrieve two counts from two separate tables into one SQL query to use with PHP. This is the current SQl query:
SELECT COUNT(entryid) AS total FROM rh_entries UNION SELECT COUNT(pentryid) AS attended FROM rh_playerentries WHERE playerid=79
This is the PHP I am using to utilize the data:
$result = mysql_query($query);
$attendance = mysql_fetch_assoc($result);
echo "Total: " . $attendance['total']
. " Attended: " . $attendance['attended']
. " Percentage: "
. (int)$attendance['total'] / (int)$attendance['attended']
. " <br />";
I am getting this output:
Warning: Division by zero in /home/content/g/V/i/gViscardi/html/guilds/sanctum/raidinfo/player.php on line 41
Total: 6 Attended: Percentage:
Apparently the $attendance['attended'] is not being set properly. Am I missing something on how UNION or COUNT or AS works?
Union combines the contents of two queries into a single table. Your queries have different column names, so the merge won't work properly. You'll want something like:
SELECT
(SELECT COUNT(entryid) FROM rh_entries) as total,
(SELECT COUNT(pentryid) FROM rh_playerentries WHERE playerid=79) as attended;
To expand on amccausl's tip, once you have that single table, you can do operations on it:
select sum(total) from
(
SELECT COUNT(entryid) FROM rh_entries as total
UNION
SELECT COUNT(pentryid) as total FROM rh_playerentries WHERE playerid=79
)
select sum(total) from
(
SELECT COUNT(entryid) total FROM rh_entries
UNION
SELECT COUNT(pentryid) total FROM rh_playerentries WHERE playerid=79
) as t;

Categories