I have two different MySQL count queries like this:
SELECT COUNT(*) AS stored_counter FROM users WHERE ***
SELECT COUNT(*) AS total_taken FROM completed WHERE ***
I'm looking for if the count value of query 1 matches the count value of query 2. Right now I am running these two queries seperately via PHP and then using PHP to see if the two queries return the same values.
But i'm looking to see if it's possible to do this with 1 SQL query?
Thanks
You can use this form
SELECT
(SELECT COUNT(*) FROM users WHERE 1 =1) stored_counter,
(SELECT COUNT(*) FROM completed WHERE 1=1) total_taken
You can add every Select statement that only gives back one Result (one field(one row one column)) only) as its own column
Related
My database is called: (training_session)
I try to print out some information from my data, but I do not want to have any duplicates. I do get it somehow, may someone tell me what I do wrong?
SELECT DISTINCT athlete_id AND duration FROM training_session
SELECT DISTINCT athlete_id, duration FROM training_session
It works perfectly if i use only one column, but when I add another. it does not work.
I think you misunderstood the use of DISTINCT.
There is big difference between using DISTINCT and GROUP BY.
Both have some sort of goal, but they have different purpose.
You use DISTINCT if you want to show a series of columns and never repeat. That means you dont care about calculations or group function aggregates. DISTINCT will show different RESULTS if you keep adding more columns in your SELECT (if the table has many columns)
You use GROUP BY if you want to show "distinctively" on a certain selected columns and you use group function to calculate the data related to it. Therefore you use GROUP BY if you want to use group functions.
Please check group functions you can use in this link.
https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html
EDIT 1:
It seems like you are trying to get the "latest" of a certain athlete, I'll assume the current scenario if there is no ID.
Here is my alternate solution:
SELECT a.athlete_id ,
( SELECT b.duration
FROM training_session as b
WHERE b.athlete_id = a.athlete_id -- connect
ORDER BY [latest column to sort] DESC
LIMIT 1
) last_duration
FROM training_session as a
GROUP BY a.athlete_id
ORDER BY a.athlete_id
This syntax is called IN-SELECT subquery. With the help of LIMIT 1, it shows the topmost record. In-select subquery must have 1 record to return or else it shows error.
MySQL's DISTINCT clause is used to filter out duplicate recordsets.
If your query was SELECT DISTINCT athlete_id FROM training_session then your output would be:
athlete_id
----------
1
2
3
4
5
6
As soon as you add another column to your query (in your example, the column called duration) then each record resulting from your query are unique, hence the results you're getting. In other words the query is working correctly.
So i have a mysql table with over 9 million records. They are call records. Each record represents 1 individual call. The columns are as follows:
CUSTOMER
RAW_SECS
TERM_TRUNK
CALL_DATE
There are others but these are the ones I will be using.
So I need to count the total number of calls for a certain week in a certain Term Trunk. I then need to sum up the number of seconds for those calls. Then I need to count the total number of calls that were below 7 seconds. I always do this in 2 queries and combine them but I was wondering if there were ways to do it in one? I'm new to mysql so i'm sure my syntax is horrific but here is what I do...
Query 1:
SELECT CUSTOMER, SUM(RAW_SECS), COUNT(*)
FROM Mytable
WHERE TERM_TRUNK IN ('Mytrunk1', 'Mytrunk2')
GROUP BY CUSTOMER;
Query 2:
SELECT CUSTOMER, COUNT(*)
FROM Mytable2
WHERE TERM_TRUNK IN ('Mytrunk1', 'Mytrunk2') AND RAW_SECS < 7
GROUP BY CUSTOMER;
Is there any way to combine these two queries into one? Or maybe just a better way of doing it? I appreciate all the help!
There are 2 ways of achieving the expected outcome in a single query:
conditional counting: use a case expression or if() function within the count() (or sum()) to count only specific records
use self join: left join the table on itself using the id field of the table and in the join condition filter the alias on the right hand side of the join on calls shorter than 7 seconds
The advantage of the 2nd approach is that you may be able to use indexes to speed it up, while the conditional counting cannot use indexes.
SELECT m1.CUSTOMER, SUM(m1.RAW_SECS), COUNT(m1.customer), count(m2.customer)
FROM Mytable m1
LEFT JOIN Mytable m2 ON m1.id=m2.id and m2.raw_secs<7
WHERE TERM_TRUNK IN ('Mytrunk1', 'Mytrunk2')
GROUP BY CUSTOMER;
Sorry if this is a really dumb question but I'm not too familiar with MYSQL syntax.
I've historically been running:
USE hg19;
SELECT DISTINCT (name2), txStart, txEnd
FROM refGene
WHERE name2 LIKE '[genename]';
which would output all entries and it was fine, except if I was looking for an entry that didn't exist, I would get a blank (which just so happened to be the same result if I disconnected from the server). This was leading to a bunch of downstream issues when I couldn't actually detect if an entry didn't exist vs my internet disconnected me.
So instead I decided to try:
USE hg19;
SELECT *, count(*) AS results
FROM (
SELECT DISTINCT (name2), txStart, txEnd
FROM refGene
WHERE name2 LIKE 'TP53'
) a;
This would now give me a 0 for results if it didn't exist (and if it didn't connect it'd remain blank). However, now for whatever reason it only displays one entry no matter what (If I query for TP53 for example, it should have two distinct entries -> however, it will give me results:2 but only display one of them). Is there a way around this? I would still like to have it displaying all distinct results.
COUNT() is a aggregate function that works on groups of rows. Without a GROUP BY clause only MySQL accepts such a statement and will return arbitrary values in the not aggregated columns - and return just one row, as you've seen.
To get your desired result, you only got to invert your logic and use a LEFT JOIN
SELECT
a.results,
b.*
FROM
(SELECT COUNT(*) results FROM refGene r1 WHERE a.name2 LIKE 'TP53') a
LEFT JOIN (
SELECT
*
FROM
refGene r2
WHERE
name2 LIKE 'TP53'
) b
ON
a.result IS NOT NULL;
If your "main" query returns no row there will be a 0 (zero) in the result column an NULL values in the columns of your "main" query.
I have a query with few joins, on running it shows 11 records.
When I run its count query (removed fields from SELECT part and put COUNT(*) there) it returns different number, 16.
Why just converting to count query returns different count than its original query?
Either you have used Select Distinct when you are getting the number of rows 11 in result.
or
you are not using distinct in Count like Count(Distinct fieldname), so Count(*) is giving all the record count.
Most probably your join query returns the same rows twice or more. You can see what i mean by executing select * from... query
I am pulling through the latest five entries in a database. I also want to show the total number of entries beside this.
Currently I'm running two queries - the first, to get the latest five:
SELECT reference.id, reference.name
FROM reference
WHERE (status = 2 OR status = 3)
ORDER BY reference.date
LIMIT 5
The second, to count the total:
SELECT COUNT(reference.status) AS complete_count
FROM reference
WHERE (status = 2 OR status = 3)
Is there any way to join these two into one? When I try and add another column to the first query's output (the COUNT), it only returns one row.
Thanks!
This should give you what you're hoping for:
SELECT reference.id, reference.name, COUNT(1) AS complete_count
FROM reference
WHERE status = 2
OR status = 3
GROUP BY reference.id, reference.name
ORDER BY reference.date
LIMIT 5
you can pull a sub select as the item so...
select foo, bar, (select count(*) from tableA) from tableA;
Keep in mind that depending on the complexity of the rest of the query this may be a fairly expensive select though.
Yes, few ways :-
select reference.id, reference.name, b.complete_count
FROM reference
JOIN
(
SELECT COUNT(reference.status) AS complete_count
FROM reference
WHERE (status = 2 OR status = 3)
) as b
WHERE ...
This method is better as it do a count, then JOIN.
The another answer proposed is going to trigger the subquery for each row,
which is less ideal.
Or you can use http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows (two queries)