how to select and sum in single sql query - php

Is it possible or another solution to sum and select multiple rows in single sql query and print with while looping like that:
$query = mysql_query("SELECT SUM(Total), * FROM table");
while ($fetch = mysql_fetch_row($query)) {
echo $fetch[a];
echo $fetch[b];
echo $fetch[c];
}

Use a JOIN with a subquery that calculates the total.
SELECT SumTotal, a.*
FROM Table a
JOIN (SELECT SUM(Total) SumTotal
FROM Table) b

Do you mean this?
SELECT (SELECT SUM(Total) FROM `table`) totalSum, a.* FROM `table` a

you can do it as what #491243 suggested
SELECT (SELECT SUM(Total) FROM `table`) AS totalSum, * FROM `table`
But this is not recommended because this will cause that SQL Engine calculate sum of the column total on each row it's selecting from the database and sending a new column with the results to php with identical values in the column totalSum fields ,
better go for 2 queries.
one for selecting the rows and the other to get the total

We can use CROSS APPLY for calculation.
SELECT SumTotal, A.*
FROM table A
CROSS APPLY (SELECT SUM(Total) SumTotal FROM Table) B

Make use of GROUP BY clause.
$query = mysql_query("SELECT *,SUM(Total) as TotalSUM FROM table GROUP BY Total");
while ($fetch = mysql_fetch_row($query)) {
echo $fetch[a];
echo $fetch[b];
echo $fetch[c];
}

Usually you want to group by a column so that you can sum by a group and then it will give you separate rows for each category_id in this example
SELECT category_id, SUM(price) as totalprice
FROM products
GROUP BY category_id

isn't it simpler and faster to sum inside the loop instead using complex query ?
you could just make simple (faster) select * from table and in your while loop make the sum while looping. it will be faster than making query with subquery

Related

php/mysql Merge 2 tables with same Columns correctly

EDIT: Thanks For JoseCarlosPB here is the solution:
SELECT
(select count(DISTINCT userscount) AS duplicates from users1)
+
(select count(DISTINCT userscount) AS duplicates from users2) AS duplicates
FROM dual;
So i have 2 tables and a mysql statement i want to merge 2 tables but there is same column in both.I think There is nothing to do in PHP code i think the problem is in the mysql statement.
my code works(no errors) but it gives unexpected output.i simply want to correctly count userscount here is what i mean:
table1 has 32 users and table2 has 44 users
i thought the output will be 76 users but it is 3244
PHP:
include 'conn00.php';
$sql = "select DISTINCT userscount, count(DISTINCT userscount) AS duplicates from users1 UNION ALL
select DISTINCT userscount, count(DISTINCT userscount) AS duplicates from users2";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["duplicates"];
}
} else {
}
table1:
users1
32
table2:
users2
44
output: 3244 i want the output to be 76
If the solution is in mysql will be better bcz i have more similar sql statements and i want apply the solution for all of it.
thanks for answering
I think you can do it this way, almost like alistaircol said
SELECT
(select count(DISTINCT userscount) AS duplicates from users1)
+
(select count(DISTINCT userscount) AS duplicates from users2) AS duplicates
FROM dual;
Please check article you need Combine two MYSQL table with same column Name
Just comparing to this you need to move count outside of UNION in order to work as you expected
Maybe you could try something like this for your query:
SELECT
(select count(DISTINCT userscount) AS duplicates from users1 group by usercount)
+
(select count(DISTINCT userscount) AS duplicates from users2 group by usercount)
FROM dual;
DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced.
More info about DUAL: https://dev.mysql.com/doc/refman/8.0/en/select.html
maybe you can change your code query into this to sum the entire counting value
include 'conn00.php';
$sql = "select sum(i) as duplicates from (
select count(DISTINCT userscount) as i from users1 union all
select count(DISTINCT userscount) as i from users2
) x";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["duplicates"];
}
} else {
}
I am not sure, if the semantics of the query was correct, but the syntax must be like this (WHERE clause goes after JOIN and ON):
SELECT users1.text1, users2.name,users2.email,
users1.username
FROM users1
INNER JOIN users2
ON users1.text1=users2.text1
WHERE users1.username = $_SESSION[username]
SELECT * from
( (select count(DISTINCT userscount) AS duplicates from users1)
union all
(select count(DISTINCT userscount) AS duplicates from users2)
) as duplicates
You can also merge in this way.hope it was helpful

While using a SELECT SUM() GROUP BY, how can I still get the individual values?

values = 2,3,4
When doing a JOIN (SELECT *, SUM(values) AS MaxValues FROM table GROUP BY id), $a = $data['MaxValues'] will equal 9 as it should. However, how can I still pull the individual values(2,3,4)? trying a foreach on $b = $data['values'] only gives me one of the values. I'm assuming because of the required GROUP BY. I'm still new to all of this. Thank you
You are looking for group_concat(), I think:
JOIN (SELECT id, SUM(values) AS MaxValues, group_concat(values) as values
FROM table
GROUP BY id)
Note: You should not be using SELECT * with GROUP BY. Only include the columns in the GROUP BY clause.
You can select both values and SUM with JOIN. Also, you don't need GROUP BY if you want to get all the values, e.g.:
SELECT value, a.sum
FROM table, (SELECT SUM(value) AS `sum` FROM table ) a;

SQL Query Syntax error?

I am trying to modify a query which results in 2 records before the modification for some reason my modification makes it not work as it return nothing.
This Query works and returns 2 record:
$query = mysql_query("SELECT * FROM `table1`
WHERE `date` = '{$eventdate->format('Y-m-d')}'
OR `date` >= CURDATE() ORDER BY id DESC");
...the I added this: JOIN table2 USING(id)
...so this final code is this:
$query = mysql_query("SELECT * FROM `table1` JOIN `table2` USING(id)
WHERE `date` = '{$eventdate->format('Y-m-d')}'
OR `date` >= CURDATE() ORDER BY id DESC");
Problem is the second one returns nothing.
Is this a syntax error? How can I get this to work? Both tables have id fields.
Make sure that table2 contains matched data, where the id is equal to the id in table1.
You can use a LEFT JOIN if this match is not required.
id in your ORDER BY is now ambiguous. There might be more errors though. Check with mysql_error()
Try This
$query = mysql_query("SELECT * FROM `table1` a,`table2` b WHERE a.id=b.id
and (`a.date` = '{$eventdate->format('Y-m-d')}' OR `a.date` >= CURDATE())
ORDER BY id DESC")
When joining two tables which have no prefixes on the column names like - table1_id, table2_id, you should use aliases like -
SELECT * FROM table1 as t1 JOIN table2 as t2 on ...
and then you can refer to the fields in the table like this - t1.id, t2.id (you can do this also without aliases( as t1) and then you should refer to the fields like - table1.id).
The problem with your script is that the 2 tables have column id and in :
ORDER BY id DESC
the engine doesn`t know from which table do you refer this id
Other suggestion of mine is when possible not to use aggregation functions in the queries(in your query the CURDATE is that type of function). Aggregation functions in SQL prevent query caching. In our case you can pass the currdate from php to the query and the query can be cached.
Hope i`ve helped.

PHP SQL JOIN Avoid ID Duplicates

I am using this code:
SELECT * FROM Table1
JOIN Table2 USING(venue_id)
WHERE table2.location = '$MyVariable'
Then to count the number of records return:
$num_rows = mysql_num_rows($result);
echo "$num_rows";
It works great but venue_id in Table1 has lots of entries and I only want it to get one per venue_id
How can I make it so it only returns 1 venue_id instance?
Use GROUP BY clause,
SELECT * FROM Table1
JOIN Table2 USING(venue_id)
WHERE table2.location = '$MyVariable'
GROUP BY `Table1`.`venue_id`

Retrieving count of column mySQL PHP

Hey guys I have a mysql table called interests with 4 columns. interestID, name, categoryID interest_desc and date. the categoryID column is linked to a seperate table. How would I use a mysql query that checked how many interests are in a certain category?
Im guessing i use some sort of count() query?
Thanks guys
Update -
$count_query_v1 = "SELECT categoryID, COUNT(*) AS total FROM interests GROUP by categoryID; "; $answer = mysql_query($count_query_v1) or die(mysql_error()); echo $answer;
Getting closer but still not perfect, i want to echo out the categoryID with the most interestID's
select category_name, count(*) as total
from interests i left join category c on c.category_id = i.category_id
group by i.category_id;
count + group by,
assuming interestID is the unique primary key,
and each interest is tied to single category (as what you have shown)
select categoryID, count(*) as total
from interests
group by categoryID;
// the above example is a simple group by ID without using inner join
output :-
categoryID, total
SELECT COUNT(interestID) FROM interests WHERE categoryID = 'yourvalue';
SELECT COUNT(interestID), categoryID FROM interests GROUP BY categoryID;
Since you are using the insert query each query will insert one record, so just count the number of insert queries you run by using a counter varialble.

Categories