Is there some way to do the following in SQL? - sql

Let's imagine that we have these 2 tables:
Table 1, with the column:
Field1
1
3
Table 2, with the column:
Field1
2
4
(Well they could also be called in any other way, but I want to represent that the type of table1.field1 is the same as table2.field1).
Would it be possible to do a SQL query that would return the following?
[1,2,3,4], I mean the numbers ordered by any criteria I would want but that criteria aplying to both tables. As far as I know ORDER BY can just ORDER by the values of a column, not by a general criteria like "from lower to higher number. And even if it could I believe the SELECT instruction can't fuse columns. I mean I think the best I could achieve with that instruction would be to get something like [(1,2),(1,4),(3,2),(3,4)] and later work on it, but this can be painful with lots of results.
And the application needs fields to be on different tables, I cannot merge them.
Any idea about how to deal with this?
Thanks a lot for your help.
Edit:
Oh, it was much easier than what I thought, with that instruction is not something hard to achieve.
Thank you everyone.

This is what the UNION statement is for. It lets you combine two SELECT statements into the same resultset:
SELECT Field1
FROM Table1
UNION ALL
SELECT Field1
FROM Table2
ORDER BY 1

can you do union all
Like below:
Select field 1
from
(Select field 1 from Table 1
Union
select field 1 from table 2)
order by field 1
Use union or Union all based on your need to repeat elements in both the tables or not.

select * from
(
select field1 as field_value from table1
union
select field2 as field_value from table2
)
order by field_value asc

Related

Join two SQL Server tables [duplicate]

This question already has answers here:
Combine two tables for one output
(2 answers)
Closed 8 years ago.
I have two tables now I need a select or join command in SQL to have the third table just like image below
My two tables are like this:
I only know a simple things about join command in SQL, should I use join or something else?
I do not want have the third table in my database, I want that for a short time (something like virtual table). Please help !
You are actually looking for UNION or UNION ALL.
First of all, there is no condition on which to JOIN tables (review your documentation on JOIN) and JOIN is used for retrieving information about one logical element, let's say Event in your case, which has details stored in more tables.
Secondly, JOIN will make one result set with all of the columns of your two tables, when actually you are not trying to get all columns, but all rows.
For this you will have to use UNION or UNION ALL like this:
SELECT
EventID,
ID,
EventName,
Date,
Pic,
Privacy
FROM Table1
UNION ALL
SELECT
PLID AS EventID,
ID AS ID,
PlaceName AS EventName,
Date AS Date,
NULL AS Pic,
NULL AS Privacy
FROM Table2
In order to sort the result you get from the result set returned by the queries above you will need to wrap your above SELECT statements with another SELECT and use a WHERE clause at that level, like below:
SELECT *
FROM (SELECT
EventID,
ID,
EventName,
Date,
Pic,
Privacy
FROM Table1
UNION ALL
SELECT
PLID AS EventID,
ID AS ID,
PlaceName AS EventName,
Date AS Date,
NULL AS Pic,
NULL AS Privacy
FROM Table2) AS Result
WHERE Date > '2014-05-26'
What you're looking to do is a UNION or UNION ALL, not a join. See: http://www.w3schools.com/sql/sql_union.asp
UNION combines two tables without connecting their content. Your example shows all 4 records from the original tables unmodified.
A JOIN solution links the two tables. It's very common and you will probably use it if you're building a relational database, but it won't give you the example result.
Since the two tables don't have identical # of columns, you have to help it out here:
SELECT EventID, EventName, Date, Pic, privacy FROM [table 1]
UNION ALL
SELECT PLID, PlaceName, Date, null, null FROM [table 2]
You want to have one table from two different tables. So you need unified result set from each by renaming column in SELECT statement:
SELECT `EventID` AS `ObjectID`, `EventName` AS `ObjectName`, .... FROM table_1 ...
similary with table_2
Then combine to one result set:
SELECT `ID` AS `ObjectID`, `EventName` AS `ObjectName`, .... FROM table_1 ...
UNION
SELECT `PlaceID` AS `ObjectID`, `PlaceName` AS `ObjectName`, .... FROM table_2 ...
My mistake, I didn't take the time to examine the pictures fully. you would have to use Union since you want to return what is in both tables.

Query multiple tables in access

We have 50 tables we need to query a column that exists in all. This column is a checkbox. We need to count per table how many are checked and how many are unchecked. Cant seem to get 1 query to count results and display per table as opposed to multiplying or combining results.
We need 1 column per table to display count of checked and unchecked.
Thanks
SELECT "Table1" , Count('qcpass') AS column
FROM 5000028
GROUP BY [5000028].qcpass
union
SELECT "Table2",count('qcpass')
FROM 5000029
Group By [5000029].qcpass;
Edit
Based on your feedback, try this (sorry, didn't realize you wanted 1 column per table):
Make a union query that combines all 50 tables. The result should be 1 row per table:
SELECT "5000028" as QCPASS, Count () FROM 5000028 group by QCPASS
UNION
SELECT "5000029" as QCPASS, Count () FROM 5000029 group by QCPASS
UNION...
Now make a "Crosstab" query which is pretty easy in Access. First, make a new query and select the Crosstab option at the top. This query will use the union query as its source.
This will have 3 columns. The first will be a constant value (you can use "Totals" if you like, it's just a placeholder). Set this as your "Row Heading".
The 2nd column will be QCPass. Set this as your "Column Heading".
The 3rd column will be Expr1. Set this as your "Value".
When you run this, you should see a 1-row table with 1 column per each of your source tables.
SELECT columna, 'tablename1' from tablename1 where ..
UNION
SELECT columna, 'tablename2' from tablename2 where ..
UNION
SELECT columna, 'tablename3' from tablename3 where ..
...
SELECT columna, 'tablename4' from tablename50 where ..

Multiple SQL SELECT

I've 10 tables with a lot of records. All tables have "Date" column. I want extract all data from tables for date.
I can do 10 queries SELECT * FROM Table1 WHERE Date=dd/MM/yyyy, ect...but I want to do only a query with "multiple selection". How can I do this?
I'm not so skilled with SQL language.
EDIT: I'm working with Microsoft Access and also MySQL (for two different desktop application, but same problem).
Tables have different fields (just Date all in common), so It's not good the use of UNION.
SELECT *
FROM table1,
table2
WHERE table1.date = 'somedate'
AND table2.date = 'somedate'
Take a look at the UNION operator for including data from multiple SELECT statements.
Your question is not so clear. Based one what i understood, you can use Union SQL statement to combine your queries and make them as a single query. But if you want to query for different dates in different tables, you can use only use multiple queries .
If I right understand your question, and you want to get data from tables where
all 10 tables contains the same list of fields, you can use
SELECT * FROM Table1 WHERE Date=dd/MM/yyyy
UNION ALL
SELECT * FROM Table2 WHERE Date=dd/MM/yyyy
UNION ALL
...
UNION ALL
SELECT * FROM Table10 WHERE Date=dd/MM/yyyy
UNION ALL
If fields are different, you need to add the fields you want to get in result set:
SELECT field1, field2 FROM Table1 WHERE Date=dd/MM/yyyy
UNION ALL
SELECT field1, field2 FROM Table2 WHERE Date=dd/MM/yyyy
UNION ALL
...
UNION ALL
SELECT field1, field2 FROM Table10 WHERE Date=dd/MM/yyyy
UNION ALL
Be careful of performance issues when using Union. -- Be sure to run some tests comparing query times of the two approaches.
Depending on your database software, you could also use a stored procedure.
And also check that the date column is indexed in each of the tables.

distinct values from multiple fields within one table ORACLE SQL

How can I get distinct values from multiple fields within one table with just one request.
Option 1
SELECT WM_CONCAT(DISTINCT(FIELD1)) FIELD1S,WM_CONCAT(DISTINCT(FIELD2)) FIELD2S,..FIELD10S
FROM TABLE;
WM_CONCAT is LIMITED
Option 2
select DISTINCT(FIELD1) FIELDVALUE, 'FIELD1' FIELDNAME
FROM TABLE
UNION
select DISTINCT(FIELD2) FIELDVALUE, 'FIELD2' FIELDNAME
FROM TABLE
... FIELD 10
is just too slow
if you were scanning a small range in the data (not full scanning the whole table) you could use WITH to optimise your query
e.g:
WITH a AS
(SELECT field1,field2,field3..... FROM TABLE WHERE condition)
SELECT field1 FROM a
UNION
SELECT field2 FROM a
UNION
SELECT field3 FROM a
.....etc
For my problem, I had
WL1 ... WL2 ... correlation
A B 0.8
B A 0.8
A C 0.9
C A 0.9
how to eliminate the symmetry from this table?
select WL1, WL2,correlation from
table
where least(WL1,WL2)||greatest(WL1,WL2) = WL1||WL2
order by WL1
this gives
WL1 ... WL2 ... correlation
A B 0.8
A C 0.9
:)
The best option in the SQL is the UNION, though you may be able to save some performance by taking out the distinct keywords:
select FIELD1 FROM TABLE
UNION
select FIELD2 FROM TABLE
UNION provides the unique set from two tables, so distinct is redundant in this case. There simply isn't any way to write this query differently to make it perform faster. There's no magic formula that makes searching 200,000+ rows faster. It's got to search every row of the table twice and sort for uniqueness, which is exactly what UNION will do.
The only way you can make it faster is to create separate indexes on the two fields (maybe) or pare down the set of data that you're searching across.
Alternatively, if you're doing this a lot and adding new fields rarely, you could use a materialized view to store the result and only refresh it periodically.
Incidentally, your second query doesn't appear to do what you want it to. Distinct always applies to all of the columns in the select section, so your constants with the field names will cause the query to always return separate rows for the two columns.
I've come up with another method that, experimentally, seems to be a little faster. In affect, this allows us to trade one full-table scan for a Cartesian join. In most cases, I would still opt to use the union as it's much more obvious what the query is doing.
SELECT DISTINCT CASE lvl WHEN 1 THEN field1 ELSE field2 END
FROM table
CROSS JOIN (SELECT LEVEL lvl
FROM DUAL
CONNECT BY LEVEL <= 2);
It's also worthwhile to add that I tested both queries on a table without useful indexes containing 800,000 rows and it took roughly 45 seconds (returning 145,000 rows). However, most of that time was spent actually fetching the records, not running the query (the query took 3-7 seconds). If you're getting a sizable number of rows back, it may simply be the number of rows that is causing the performance issue you're seeing.
When you get distinct values from multiple columns, then it won't return a data table. If you think following data
Column A Column B
10 50
30 50
10 50
when you get the distinct it will be 2 rows from first column and 1 rows from 2nd column. It simply won't work.
And something like this?
SELECT 'FIELD1',FIELD1, 'FIELD2',FIELD2,...
FROM TABLE
GROUP BY FIELD1,FIELD2,...

SQL select from data in query where this data is not already in the database?

I want to check my database for records that I already have recorded before making a web service call.
Here is what I imagine the query to look like, I just can't seem to figure out the syntax.
SELECT *
FROM (1,2,3,4) as temp_table
WHERE temp_table.id
LEFT JOIN table ON id IS NULL
Is there a way to do this? What is a query like this called?
I want to pass in a list of id's to mysql and i want it to spit out the id's that are not already in the database?
Use:
SELECT x.id
FROM (SELECT #param_1 AS id
FROM DUAL
UNION ALL
SELECT #param_2
FROM DUAL
UNION ALL
SELECT #param_3
FROM DUAL
UNION ALL
SELECT #param_4
FROM DUAL) x
LEFT JOIN TABLE t ON t.id = x.id
WHERE x.id IS NULL
If you need to support a varying number of parameters, you can either use:
a temporary table to populate & join to
MySQL's Prepared Statements to dynamically construct the UNION ALL statement
To confirm I've understood correctly, you want to pass in a list of numbers and see which of those numbers isn't present in the existing table? In effect:
SELECT Item
FROM IDList I
LEFT JOIN TABLE T ON I.Item=T.ID
WHERE T.ID IS NULL
You look like you're OK with building this query on the fly, in which case you can do this with a numbers / tally table by changing the above into
SELECT Number
FROM (SELECT Number FROM Numbers WHERE Number IN (1,2,3,4)) I
LEFT JOIN TABLE T ON I.Number=T.ID
WHERE T.ID IS NULL
This is relatively prone to SQL Injection attacks though because of the way the query is being built. It'd be better if you could pass in '1,2,3,4' as a string and split it into sections to generate your numbers list to join against in a safer way - for an example of how to do that, see http://www.sqlteam.com/article/parsing-csv-values-into-multiple-rows
All of this presumes you've got a numbers / tally table in your database, but they're sufficiently useful in general that I'd strongly recommend you do.
SELECT * FROM table where id NOT IN (1,2,3,4)
I would probably just do:
SELECT id
FROM table
WHERE id IN (1,2,3,4);
And then process the list of results, removing any returned by the query from your list of "records to submit".
How about a nested query? This may work. If not, it may get you in the right direction.
SELECT * FROM table WHERE id NOT IN (
SELECT id FROM table WHERE 1
);