Mysql combine two results and group them by field - mysql

I have been trying but it seems I am missing something. I want to combine two results from two tables by a common field.
I would like to group results from these two queries by customer field.
SELECT errors.customer, count(errors.customer) as err_count,severity from errors group by customer,severity;
SELECT customer,sum(size) as Tot_size,count(customer) as Policy_count from backup group by customer;
I have tried this.
SELECT errors.customer, count(errors.customer) as err_count,severity from errors group by customer,severity union all SELECT customer,count(customer) as Policy_count ,sum(size) as Tot_size from backup group by customer;
But for some reason some columns are missing.

You should follow the requirements for union:
The UNION operator is used to combine the result-set of two or more SELECT statements.
Each SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
Apparently, the above items are not satisfied in your query.

Try something like this:
SELECT q1.customer, Tot_size, Policy_count, err_count, severity
FROM ( SELECT customer, SUM(size) AS Tot_size, COUNT(customer) AS Policy_count
FROM backup GROUP BY customer ) q1
LEFT JOIN ( SELECT customer, COUNT(customer) AS err_count, severity
FROM errors GROUP BY customer, severity ) q2 ON q1.costumer = q2.costumer

Your first query contains three columns and your second one contains two columns.
In order to use the UNION operator your two queries need to have the same amount of columns, and the columns should be compatible.
In your case the second query lacks a third column. If there is no corresponding column to use you can set a default such as
"'n/a' as severity "
if it should be textual or
"0 as severity "
for a numerical value.
Cheers Martin

Related

Mysql DISTINCT with more than one column (remove duplicates)

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.

Adding values after a MySQL query?

I have created a query that gets two values. It outputs the correct values but now i want to add these values together to get one value in a column named "Total Cost". Is this possible if "Total Cost" is not a column in my tables?
Here is the query i used:
SELECT ROUND(SUM(drugcost_cost),0) FROM drugcost UNION SELECT ROUND(SUM(operation_cost),0) FROM operation
Do this with subqueries:
SELECT d.dcost, o.ocost, (d.dcost + o.ocost) as totalcost
FROM (SELECT ROUND(SUM(drugcost_cost),0) as dcost FROM drugcost) d CROSS JOIN
(SELECT ROUND(SUM(operation_cost),0) as ocost FROM operation) o;
By the way, your query is an excellent example of why you should always use union all unless you really know why you want union instead. If the values from the two subqueries are the same, then union will remove duplicates -- and you will get only one row.

MySQL Get list with values from two columns

Say I have this table with two columns. Both columns contain IP-addresses. I want a SELECTquery that gets me a list of all ip-addresses that occur in either the first column, or the second column, or both. Just a list of all distinct ip-addresses in that table. How is that done? I would have thought that SELECT DISTINCT ip_src, ip_dst FROM table would have done the trick.
Note that your example only applies the distinct to ip_src. To get just one column try a UNION:
SELECT ip_src FROM table
UNION
SELECT ip_dst FROM table
As noted in the comments not only will the UNION remove duplicates between the columns but also those that occur with the columns meaning using a DISTINCT is unnecessary.

mysql query two tables, UNION and where clause

I have two tables.
I query like this:
SELECT * FROM (
Select requester_name,receiver_name from poem_authors_follow_requests as one
UNION
Select requester_name,receiver_name from poem_authors_friend_requests as two
) as u
where (LOWER(requester_name)=LOWER('user1') or LOWER(receiver_name)=LOWER('user1'))
I am using UNION because i want to get distinct values for each user if a user exists in the first table and in the second.
For example:
table1
nameofuser
peter
table2
nameofuser
peter
if peter is on either table i should get the name one time because it exists on both tables.
Still i get one row from first table and a second from table number two. What is wrong?
Any help appreciated.
There are two problems with your SQL:
(THis is not the question, but should be considered) by using WHERE over the UNION instead of the tables, you create a performance nightmare: MySQL will create a temporary table containing the UNION, then query it over the WHERE. Using a calculation on a field (LOWER(requester_name)) makes this even worse.
The reason you get two rows is, that UNION DISTINCT will only suppress real duplicates, so the tuple (someuser,peter) and the tuple (someotheruser, peter) will result in duplication.
Edit
To make (someuser, peter) a duplicate of (peter, someuser) you could use:
SELECT
IF(requester_name='peter', receiver_name, requester_name) AS otheruser
FROM
...
UNION
SELECT
IF(requester_name='peter', receiver_name, requester_name) AS otheruser
FROM
...
So you only select someuser which you already know : peter
You need the where clause on both selects:
select requester_name, receiver_name
from poem_authors_follow_requests
where LOWER(requester_name) = LOWER('user1') or LOWER(receiver_name) = LOWER('user1')
union
select requester_name, receiver_name
from poem_authors_friend_requests
where LOWER(requester_name) = LOWER('user1') or LOWER(receiver_name) = LOWER('user1')
The two queries are independent of each other, so you shouldn't try to connect them other than by union.
You can use UNION if you want to select rows one after the other from several tables or several sets of rows from a single table all as a single result set.
UNION is available as of MySQL 4.0. This section illustrates how to use it.
Suppose you have two tables that list prospective and actual customers, a third that lists vendors from whom you purchase supplies, and you want to create a single mailing list by merging names and addresses from all three tables. UNION provides a way to do this. Assume the three tables have the following contents:
http://w3webtutorial.blogspot.com/2013/11/union-in-mysql.html
You are doing the union before and then applying the where clause. So you would get a unique combination of "requester_name,receiver_name" and then the where clause would apply. Apply the where clause in each select...
Select requester_name,receiver_name from poem_authors_follow_requests
where (LOWER(requester_name)=LOWER('user1')
or LOWER(receiver_name)=LOWER('user1'))
UNION
Select requester_name,receiver_name from poem_authors_friend_requests
where (LOWER(requester_name)=LOWER('user1')
or LOWER(receiver_name)=LOWER('user1'))
In your where statement, reference the alias "u" for each field refence in your where statement.
So the beginning of your where statement would be like: where (LOWER(u.requester_name) = ...
This is simlar to the answer you can see in: WHERE statement after a UNION in SQL?
You should be able to use the INTERSECT keyword instead of doing a nested query on a UNION.
SELECT member_id, name FROM a
INTERSECT
SELECT member_id, name FROM b
can simply be rewritten to
SELECT a.member_id, a.name
FROM a INNER JOIN b
USING (member_id, name)
http://www.bitbybit.dk/carsten/blog/?p=71

A problem with UNION Query Usage

The issue here is suppose if i want to use two queries seperated by UNION, the query is as
$query=(select a.name,a.age,b.country,b.state from a,b where a.aid=b.bid) UNION (select a.name,a.age,c.profession,c.salary from a,c where a.anid=c.cid)
here the result would only show the first query's result , Any way in which i could display the result of 2nd query also down to the result of first query using UNION. Expecting any help on this. Thanks
Are you after
(
select a.name,a.age,b.country,b.state,null as profession,null as salary
from a,b
where a.aid=b.bid
)
UNION
(
select a.name,a.age,null,null,c.profession,c.salary
from a,c
where a.anid=c.cid
)
You will have null in the profession and salary columns from the first query and null in country and state columns in the second query
Try this
$query=(select a.name,a.age,b.country,b.state from a,b where a.aid=b.bid UNION select a.name,a.age,c.profession,c.salary from a,c where a.anid=c.cid)
by the way the fields in both select must be the same datatype
As I understood it a union was to do the same query on two different tables. If you get a result from the first half of the union you will not get the results from the second half.
Basic property of UNION is
Selected columns listed in
corresponding positions of each SELECT
statement should have the same data
type. (For example, the first column
selected by the first statement should
have the same type as the first column
selected by the other statements.)
If the data types of corresponding
SELECT columns do not match, the types
and lengths of the columns in the
UNION result take into account the
values retrieved by all of the SELECT
statements. For example, consider the
following: