How to perform union operation between two tables? - mysql

After performing union operator between two tables in which the columns in one of the table are empty the result is displaying from second row... i dont why why is this happening ...? can anyone clarify my doubt?
my tables are sample1 and sample2
Both table contains Id, Empname , Location
data in table is
101 Null NUll
102 aaaa sec
data in table2 is
103 bbbb hyd
102 cccc gdv
Query:
(select EmpName,Location
from sample1)
union
(select EmpName,Location
from sample2)
Output
EMPNAME LOCATION
aaaa sec
bbbb hyd
cccc gdv

To remove the null records from the result, try this:
(select EmpName,Location
from sample1
WHERE EmpName IS NOT NULL
AND Location IS NOT NULL)
union
(select EmpName,Location
from sample2
WHERE EmpName IS NOT NULL
AND Location IS NOT NULL)
Result:
EMPNAME LOCATION
vijay ngdv
suresh hyd
ajay hyd
See result in SQL Fiddle.
EDIT:
I guess the record contains empty string or white spaces instead of null. So try this:
(select EmpName,Location
from sample1
WHERE LENGTH(TRIM(EmpName)) >0
AND LENGTH(TRIM(Location)) >0)
union
(select EmpName,Location
from sample2
WHERE LENGTH(TRIM(EmpName)) >0
AND LENGTH(TRIM(Location)) >0)
See result in SQL Fiddle.
Explanation:
LENGTH(TRIM(EmpName)) will return the length of the field EmpName after removing white spaces from it.

How to perform union operation between two tables?
you have to use union operator with following circumstances,
1.You have similar information in multiple tables and you want to retrieve rows from all of
them at once.
2.You want to select several sets of rows from the same table, but the conditions that
characterize each set aren't easy to write as a single WHERE clause. UNION allows retrieval
of each set with a simpler WHERE clause in its own SELECT statement; the rows retrieved by
each are combined and produced as the final query result.
Note : its not the perfect answer for your question but it helps in understanding of union
operator
please see this http://www.mysqlfaqs.net/mysql-faqs/Funtions-and-Operators/How-does-union-work-in-MySQL

Related

mysql order by custom field with and list also these fields which are missing in custom list

I would like to make a query for mysql:
select field1, count(*) as c
from temporary table
group by field1
order by field(field1, 'XXX', 'YYY', 'ZZZ')
so this makes a nice group i.e.:
XXX ZZZ
454 321
But, if there isn't any YYY values, because count(*) for YYY "returns 0", this is not listed like the XXX and ZZZ and should not be skipped because empty (or null) fields.
but I would like this output:
XXX YYY ZZZ
454 0 321
is that possible only in mysql?
Thanks a lot in advance!
Don't use SELECT * but the list of your fields SELECT fields, fields1, fields2
If your result is NULL or 0 you will have your column

count comma-separated values from a column - sql

I want count the length of a comma separated column
I have use these
(LENGTH(Col2) - LENGTH(REPLACE(Col2,",","")) + 1)
in my select query.
Demo:
id | mycolumn
1 2,5,8,60
2 4,5,1
3 5,Null,Null
query result for first two row is coming correctly.for 1 = 4 ,2 = 3 but for 3rd row it is calculating null value also.
Here is what I believe the actual state of your data is:
id | mycolumn
1 2,5,8,60
2 4,5,1
3 NULL
In other words, the entire value for mycolumn in your third record is NULL, likely from doing an operation involving a NULL value. If you actually had the text NULL your current query should still work.
The way to get around this would be to use COALESCE(val, "") when handling the NULL values in your strings.
Crude way of doing it is to replace the occurances of ',Null' with nothing first:-
SELECT a.id, (LENGTH(REPLACE(mycolumn, ',Null', '')) - LENGTH(REPLACE(REPLACE(mycolumn, ',Null', ''),",","")) + 1)
FROM some_table a
If the values refer to the id of rows in another table then you can join against that table using FIND_IN_SET and then count the matches (assuming that the string 'Null' is not an id on that other table)
SELECT a.id, COUNT(b.id)
FROM some_table a
INNER JOIN id_list_table b
ON FIND_IN_SET(b.id, a.mycolumn)
GROUP BY a.id

Comparing attributes from the same table using SQL query

I have a contents table and the entires in it are as shown in the attached figure
There are more than 100,000 entries. I want to fetch the data where the update_date for commit=0 is greater than update_date for commit=1. I also need the corresponding row for commit=1.
I tried a few things, but takes a long time to retrieve the results. What is the best SQL query I can use. I am using MySQL database.
EDIT
I have now updated the table. There is an attribute called content_id which binds the rows together.
A query like this gives me half of what I want
select a.* from contents a, contents b where
a.content_id=b.content_id and
a.update_date > b.update_date and
a.committed=0 and b.committed=1
I also want the corresponding entries from committed=1, but they should be appended at the bottom as rows and not vertically concatenated as columns.
For example, I cannot use
select * from contents a, contents b where
a.content_id=b.content_id and
a.update_date > b.update_date and
a.committed=0 and b.committed=1
because the results from 'b' are appended vertically. Also, is there a better way to write this query. This works really slow if there are many entries in the database.
I am assuming that in the above example, you only need id=2 as for content id = 1, the update_date for commit=0 is greater than update_date for commit=1 and in that case you need data for commited = 1.
I an using Oracle, so you need to find a suitable replacement for row_number() funtion in mysql.
The logic would be
Create a view on the existing table to use rownumber so it will give rownumber like below order by time desc (see if you use a nested query to do it)
ID, CONTENT_ID, COMMITED, UPDATE_DATE, ROWN
2 1 1 06-SEP-15 00:00:56 1
1 1 0 07-SEP-15 00:00:56 2
3 2 0 03-SEP-15 00:00:56 1
4 2 1 04-SEP-15 00:00:56 2
Now select only rows where where rown=1 and commited=1
This is the query in oracle. The second with query c2 will be your view.
Oracle query
with c1 (id, content_id,commited,update_date) as
(
select 1,1,0,sysdate from dual union
select 2,1,1,sysdate-1 from dual union
select 3,2,0,sysdate-4 from dual union
select 4,2,1,sysdate-3 from dual
),
c2 as
(select c1.*,row_number() over(partition by content_id order by update_date) as rown from c1)
select id,content_id,commited,update_date from c2
where rown=1 and commited=1
ID, CONTENT_ID, COMMITED, UPDATE_DATE, ROWN
Output
ID, CONTENT_ID, COMMITED, UPDATE_DATE
2 1 1 06-SEP-15 00:06:17

How to return ordered data from multiple records into one record in MySQL?

I have a MySQL database with a table of survey responses with three important fields (renamed for clarity): SURVEY_TAKER_ID, QUESTION_NUMBER, and RESPONSE. Assuming a 3-question survey as an example, it would look something like this:
SURVEY_TAKER_ID | QUESTION_NUMBER | RESPONSE
----------------------------------------
101 1 Apple
102 1 Orange
103 1 Banana
101 2 Morning
102 2 Evening
103 2 Afternoon
101 3 Red
102 3 Blue
103 3 Yellow
I would like to create a SELECT query that outputs each survey taker's ID and responses in order by question number, e.g.:
101,Apple,Morning,Red
102,Orange,Evening,Blue
103,Banana,Afternoon,Yellow
I know that SQL Server has FOR XML, which can make this easier, but my database is in MySQL, and I must admit that I'm not really all that adept at SQL in the first place. Can anyone please give me a sample query that would produce the output above, or point me to a way to do it?
Many thanks to anyone who can help...
...Jay
SURVEY_TAKER_ID with "Question_Number: RESPONSE" style concating:
SQL Fiddle
SELECT SURVEY_TAKER_ID
,GROUP_CONCAT(CONCAT(QUESTION_NUMBER, ': ', RESPONSE) ORDER BY QUESTION_NUMBER SEPARATOR ', ') AS RESPONSES
FROM Table1
GROUP BY SURVEY_TAKER_ID
ORDER BY SURVEY_TAKER_ID
.
SURVEY_TAKER_ID with "RESPONSE" alone style concating:
SQL Fiddle
SELECT SURVEY_TAKER_ID
,GROUP_CONCAT(RESPONSE ORDER BY QUESTION_NUMBER SEPARATOR ', ') AS RESPONSES
FROM Table1
GROUP BY SURVEY_TAKER_ID
ORDER BY SURVEY_TAKER_ID
Try this:
SELECT CONCAT(SURVEY_TAKER_ID, ',', RESPONSE)
FROM (SELECT SURVEY_TAKER_ID, GROUP_CONCAT(RESPONSE) RESPONSE
FROM (SELECT * FROM SURVEY ORDER BY SURVEY_TAKER_ID, QUESTION_NUMBER) A
GROUP BY SURVEY_TAKER_ID
) A

mysql select update

Got this:
Table a
ID RelatedBs
1 NULL
2 NULL
Table b
AID ID
1 1
1 2
1 3
2 4
2 5
2 6
Need Table a to have a comma separated list as given in table b. And then table b will become obsolete:
Table a
ID RelatedBs
1 1,2,3
2 4,5,6
This does not rund through all records, but just ad one 'b' to 'table a'
UPDATE a, b
SET relatedbs = CONCAT(relatedbs,',',b.id)
WHERE a.id = b.aid
UPDATE: Thanks, 3 correct answers (marked oldest as answer)! GROUP_CONCAT is the one to use. No need to insert commas between the ids using relatedids = CONCAT(relatedids,',',next_id) that is done automatic by GROUP_CONCAT.
You'll have to use the mysql group_concat function in order to achieve this: http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_group-concat
Look into GROUP_CONCAT(expr)
mysql> SELECT student_name,
-> GROUP_CONCAT(DISTINCT test_score
-> ORDER BY test_score DESC SEPARATOR " ")
-> FROM student
-> GROUP BY student_name;
You can't do that in standard SQL. You could write a stored procedure to do that. I had a similar problem, but I was using PostgreSQL so I was able to resolve it by writing a custom aggregate function so that you can do queries like
select aid, concat(id)
from b group by
aid
Update: MySQL has a group_concat aggregate function so you can do something like
SELECT id,GROUP_CONCAT(client_id) FROM services WHERE id = 3 GROUP BY id
as outlined here.