mysql query two tables, UNION and where clause - mysql

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

Related

SELECT multiple columns from multiple tables and don't fill blank spaces

I have what I believe to be a pretty unique use case. I would like to be able to runs a single SELECT statement on a database where I get one column from four tables. I need to run where clauses on each different table where I have one main clause that will be across each of the tables and I am not able to JOIN because the data in each column will be a different length and I don't want to have duplicate items.
I have an example of the Select statement below. Also I understand if this is not possible.
SELECT s.service_id, u.id AS "user_id", h.mac_address, l.id AS "location_id" FROM services s
LEFT JOIN db.av_product ap ON s.product_id = ap.id
WHERE s.customer_code LIKE 'test_customer'
AND u.customer_code LIKE 'test_customer'
AND h.customer_code LIKE 'test_customer'
AND l.customer_code LIKE 'test_customer'
AND s.parent_id IS NULL
AND s.active=0
AND ap.sku NOT REGEXP 'fakeregex'
AND l.active = "1"
AND h.hardware_id NOT IN ('44','45')
AND (u.support_user != 1 OR u.support_user IS NULL);
TIA!
You will need to use joins for your tables to make a single query OR you can try multiple queries merged with UNION keyword.
If you want to make a single query, have a look about SELECT DISTINCT or GROUP BY for handling duplicates.
wut up?
do you know what UNION is?
The UNION operator is used to combine the result-set of two or more SELECT statements.
but every SELECT statement within UNION must have the same number of columns; so there we got a problem.
you can handle it with WHERE operator so I won't get in to it.
anyway, UNION!
shall we?
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
anyway; your solution is UNION, maybe not like what I wrote.
you can try this link too.
https://www.w3schools.com/mysql/mysql_union.asp
have a clean code

Mysql combine two results and group them by field

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

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 Join Table Without UNION

Can anyone help me on how could I join two tables without merging the result into single row? Please see below query:
SELECT *
FROM resorderdetails rd
INNER JOIN resinvalidorderdetails ri
ON rd.itemid=ri.srcitemid;
Let say for example I have 1 row in resorderdetails table with field itemid=1 and I have 1 row in resinvalidorderdetails table with field srcitemid=1.
If we will going to execute the above query, it will return a result of single row [merging the data of two tables]
What I want to do is to have two rows as a result. The first row is the record came from resorderdetails and the other row is the record came from resinvalidorderdetails without using UNION ALL or UNION.
How could I do it? Is it possible?
It's not possible, because you wannna have :
SELECT * FROM resorderdetails rd
and
select * from resinvalidorderdetails
There are only joins operations and UNION which you don't want to use, and the JOINS will put together or remove commons ids and UNION will do exactly what you want
Beside to display a query with 2+ tables you need something in common(even the union need same number of columns).

SELECT command in mysql

I was wondering if there is a way to do something like selecting all without ... some columns here
something like SELECT */column1,column2 , is there a way to do this ?
I just need to output something like
column1 , column2 ( from another table ) , here all other columns without column1 ( or something to make the select skip the first few columns)
EDIT:
The thing is that i need this to be dynamic , so i cant just select what i don't know. I never know how many columns there will be , i just know the 1st and the 2nd column
EDIT: here is a picture http://oi44.tinypic.com/xgdyiq.jpg
I don't need the second id column , just the last column like i have pointed.
Start building custom views, which are geared aorund saving developers time and encapsulating them from the database schema.
Oh, so select all but certain fields. You have two options.
One is a little slow.. Copy the table, drop the fields you don't want, then SELECT *
The other is to build the field list from a subquery to information_schema or something, then remove occurrences of 'field_i_dont_want' in that list.
SELECT ( SELECT THE TABLES YOU WANT AND CONCAT INTO ONE STRING ) FROM TABLE
If you need to combine records from multiple tables, you need to find a way to relate them together. Primary Keys, Foreign Keys, or anything common among this.
I will try to explain this with a sql similar to your problem.
SELECT table1.id, table2.name, table1.column3, table1.column4
FROM table1
INNER JOIN table2 On table2.commmonfield = table1.commonfield
If you have 'n' columns in your table as in Col1,Col2,Col3....Coln you can select whatever columns you want to select from the table.
SELECT Col1,Col2 FROM YOURTABLE;
You either select all columns (*) or especify the columns you want one by one. There is no way to select 'all but some'.
The SQL language lets you either select a wildcard set of columns or enumerated single columns from a singular table. However you can join a secondary table and get a wildcard there.
SELECT
a.col1,
b.*
FROM
table_a as a
JOIN table_b as b ON (a.col5 = b.col_1)