Query to join two tables with like operator - sql

I have two table which has data as below
Table1
+-----+-------+-------------------------+
| ID | value | Test |
+-----+-------+-------------------------+
| 200 | 2456 | yyy xxcv zuio uio tzrue |
| 201 | 2905 | xxx tttt ssrt uio uioe |
| 203 | 34567 | zzz iii ool uiol werts |
| 204 | 2356 | xxx tttt ssrt uio wertz |
| 205 | 3478 | io ser xcv erto klop |
| 206 | 4567 | xxx tttt ssrt uio poiu |
| 207 | 234 | zzz iii ool uiol wert |
+-----+-------+-------------------------+
I would like to create where clause to get rows with like operator.
for ex.
select *
from Table1
where test like '%xxcv zuio%' Or Like '%iii ool%' OR '%xcv erto%' OR '%ssrt uio%' OR '%uio uioe%'
But my problem is that there are more than 15-20 different parameter in where clause, it can also increase latter.
So I have decided to create a new table in database lets called it Table2 with parameter as shown below.
Table2
+----+-----------+
| ID | Parameter |
+----+-----------+
| 20 | xxcv zuio |
| 21 | iii ool |
| 22 | xcv erto |
| 23 | ssrt uio |
| 24 | uio uioe |
+----+-----------+
My question is how can I join this table to give the same result like above query.
I am still learning joins so any advice will be helpful.

You can use exists:
select t1.*
from Table1 t1
where exists (select 1 from table2 t2 where t1.test like concat('%', t2.parameter, '%'))

I don't think using a join is helping in this scenario, and this kind of text searching is not a strong point for SQL Server. Consider building an elasticsearch index or using another system that supports text searching as a primary use case (SQL Server does support full text search if that feature is enabled, but I've always been warned away from it, so don't have experience with it.)
If staying within TSQL is desirable for your particular situation, then I would use the awkward "OR LIKE" syntax. What it lacks in elegance it makes up for in readability.

Related

How to select table with a concatenated column?

I have the following data:
select * from art_skills_table;
+----+------+---------------------------+
| ID | Name | skills |
+----+------+---------------------------|
| 1 | Anna | ["painting","photography"]|
| 2 | Bob | ["drawing","sculpting"] |
| 3 | Cat | ["pastel"] |
+----+------+---------------------------+
select * from computer_table;
+------+------+-------------------------+
| ID | Name | skills |
+------+------+-------------------------+
| 1 | Anna | ["word","typing"] |
| 2 | Cat | ["code","editing"] |
| 3 | Bob | ["excel","code"] |
+------+------+-------------------------+
I would like to write an SQL statement which results in the following table.
+------+------+-----------------------------------------------+
| ID | Name | skills |
+------+------+-----------------------------------------------+
| 1 | Anna | ["painting","photography","word","typing"] |
| 2 | Bob | ["drawing","sculpting","excel","code"] |
| 3 | Cat | ["pastel","code","editing"] |
+------+------+-----------------------------------------------+
I've tried something like SELECT * from art_skills_table LEFT JOIN computer_table ON name. However it doesn't give what I need. I've read about array_cat but I'm having a bit of trouble implementing it.
if the skills column from both tables are arrays, then you should be able to get away with this:
SELECT a.ID, a.name, array_cat(a.skills, c.skills)
FROM art_skills_table a LEFT JOIN computer_table c
ON c.id = a.id
That said, While you used LEFT join in your sample, I think either an INNER or FULL (OUTER) join might serve you better.
First, i wondered why the data are stored in such a model.
Was of the opinion that NoSQL databases lack ability for joins and ...
... a semantic triple would be in the form of subject–predicate–object.
... a Key-value (KV) stores use associative arrays.
... a relational database would be normalized.
A few information about the use case would have helped.
Nevertheless, you can select the data with CONCAT and REPLACE for the desired form.
SELECT art_skills_table.ID, computer_table.name,
CONCAT(
REPLACE(art_skills_table.skills, '}',','),
REPLACE(computer_table.skills, '{','')
)
FROM art_skills_table JOIN computer_table ON art_skills_table.ID = computer_table.ID
The query returns the following result:
+----+------+--------------------------------------------+
| ID | Name | Skills |
+----+------+--------------------------------------------+
| 1 | Anna | {"painting","photography","word","typing"} |
| 2 | Cat | {"drawing","sculpting","code","editing"} |
| 3 | Bob | {"pastel","excel","code"} |
+----+------+--------------------------------------------+
I've used the ID for the JOIN, even though Bob has different values.
The JOIN should probably be done over the name.
JOIN computer_table ON art_skills_table.Name = computer_table.Name
BTW, you need to tell us what SQL engine you're running on.

Joining Two SQL Tables on Different Databases [duplicate]

This question already has answers here:
Can we use join for two different database tables?
(2 answers)
Closed 4 years ago.
I have two tables on two separate databases. We will call them Table1 and Table2.
Table1:
+----------+----------+----------+---------+------+----------+
| UniqueID | Date1 | Date2 | Fruit | Cost | Duration |
+----------+----------+----------+---------+------+----------+
| 1 | 09/10/18 | 10/20/18 | Apples | 1.50 | 7 |
| 2 | 09/18/18 | 10/25/18 | Oranges | 1.75 | 10 |
| 3 | 10/01/18 | 10/30/18 | Bananas | 2.00 | 10 |
+----------+----------+----------+---------+------+----------+
Table2:
+----------+---------+------+----------+-----------+
| Date1 | Fruit | Cost | Duration | New Price |
+----------+---------+------+----------+-----------+
| 09/10/18 | Savory | 1.50 | 7 | 1.90 |
| 09/18/18 | Citrusy | 1.75 | 10 | 2.50 |
| 10/01/18 | Mealy | 2.00 | 10 | 2.99 |
| 10/20/18 | Savory | 1.50 | 7 | 3.90 |
| 10/25/18 | Citrusy | 1.75 | 10 | 4.50 |
| 10/30/18 | Mealy | 2.00 | 10 | 5.99 |
+----------+---------+------+----------+-----------+
What I need the output to look like:
+----------+----------+--------------------+----------+--------------------+
| UniqueID | Date1 | New Price on Date1 | Date2 | New Price on Date2 |
+----------+----------+--------------------+----------+--------------------+
| 1 | 09/10/18 | 1.90 | 10/20/18 | 3.90 |
| 2 | 09/18/18 | 2.50 | 10/25/18 | 4.50 |
| 3 | 10/01/18 | 2.99 | 10/30/18 | 5.99 |
+----------+----------+--------------------+----------+--------------------+
I need to first convert table1.fruit to the representation of table2.fruit (apples-->savory, oranges-->citrusy, bananas-->mealy) then join on table1.fruit = table2.fruit, table1.duration = table2.duration, table1.cost = table2.cost, table1.date1 = table2.date1, and table1.date2 = table2.date1.
I don't know where to start on writing the statement. I looked over some previous questions posted here, but they really just go over the basics of linking two tables from different databases. Do I convert the table1.fruit first in the select statement, then join, or do I convert table1.fruit in the join statement? How do I join table2.date1 on both table1.date1 and table1.date2 to get the price associated with both dates?
If I can provide any more information for you, please let me know.
I am on SQL Server 2017 using Management Studio.
Thanks for any help in advance!
Create a mapping table to bridge between the different codes for fruits.
IF OBJECT_ID('tempdb..#FruitMappings') IS NOT NULL
DROP TABLE #FruitMappings
CREATE TABLE #FruitMappings (
Table1Fruit VARCHAR(100),
Table2Fruit VARCHAR(100))
INSERT INTO #FruitMappings (
Table1Fruit,
Table2Fruit)
VALUES
('Apples', 'Savory'),
('Oranges', 'Citrusy'),
('Bananas', 'Mealy')
SELECT
T1.*
--, whichever columns you need
FROM
Database1.Schema1.Table1 AS T1
INNER JOIN #FruitMappings AS F ON T1.Fruit = F.Table1Fruit
INNER JOIN Database2.Schema2.Table2 AS T2 ON
F.Table2Fruit = T2.Fruit AND
T1.Cost = T2.Cost AND
T1.Duration = T2.Duration
-- AND any other matches you need
You can use LEFT JOIN or even FULL JOIN, depending if you might have some fruits on a table that aren't available on the other (careful with NULL values if FULL JOIN).
If both databases are on the same SQL Server instance and your SQL Server login has access to both databases you can just use the full form of the object names:
select * -- Whatever...
from Database1.dbo.Table1 t1
inner join Database2.dbo.Table2 t2
on t1,UniqueId = t2.UniqueId -- Or whatever your join condition is
(adding where etc. clauses as required.)
This assumes both databases are using the default schema, otherwise replace dbo as necessary.
If the databases are on different servers you can use linked servers, but there are performance implications (the whole remote table may be read because the optimiser can't do much to filter it).

How can I join three tables in SQL?

I'm faced with following problem, I'm not sure how to tackle it. I have a rough idea, but I'm not sure how I would execute it.
Here is the issue
Table A exist in the following format:
Name | Name_Att| Name2 | Name_Att2
--------+---------+-------+-------
ryan | red | xyz | green
Likewise Table B exist in this format:
Name | Name_id |
--------+---------+
ryan | 123 |
xyz | 129 |
Likewise Table C exist in this format:
Name_Att| C_id | Name_id
--------+---------+---------
red | 4591 | 123
green | 4592 | 123
blue | 4593 | 123
green | 4594 | 129
blue | 4595 | 129
So I'm trying to create the following table:
Name_id | C_id |Name_id2 | C_id2
--------+---------+---------+----------
123 | 4591 | 129 | 4594
Is there any way I should go about this? I was thinking about writing code to do this. I'm sure there is SQL way to accomplish this. However I'm not sure.
Try to include the following joins in your solution:
FROM (TableA INNER JOIN TableB ON TableA.Name = TableB.Name)
INNER JOIN TableC ON (TableA.Name_Att = TableC.Name_Att) AND
(TableB.Name_id = TableC.Name_id)
You can do the same thing to get Name_Id2 and C_id2; make sure to alias your table names correctly.

SQL Query to get User Defined Fields joined into one row

Dearest genius folk,
I have a vendor table, and a UDF (User Defined Functions) table. I need to query some data from the vendor table as well as data from the UDF table. Now, there will be more than one UDF result per vendor_id. (vendor_id and ud_join are the links between tables).
Vendor Table
| vendor_id | vendor_name | vendor_address | vendor_status |
-----------------------------------------------------------------
| 1234 | ABC Company | 123 Fourth St. | Active |
UDF Table
| udjoin | udtype | udindex | udvalue |
-----------------------------------------------
| 1234 | VN | 36 | Data36 |
-----------------------------------------------
| 1234 | VN | 53 | Data53 |
-----------------------------------------------
| 1234 | VN | 67 | Data67 |
I want to query the vendor_id of "1234", with a returned result of:
| vendor_id | vendor_name | vendor_address | vendor_status | udf_36 | udf_53 | udf_67 |
--------------------------------------------------------------------------------------------------
| 1234 | ABC Company | 123 Fourth St. | Active | Data36 | Data53 | Data67 |
Hopefully this can be done with a basic query.
Thank you in advance for all of your assistance.
You may want to investigate the PIVOT operation; its availability and precise semantics depends upon the RDBMS you are using. Here are a few useful links to get you started:
SQL Server: https://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx
Oracle: http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html
If you search the stackoverflow archives for "SQL Pivot" you will find many related questions.
You need to transpose the data, Use PIVOT feature in SQL. Please refer
https://www.simple-talk.com/blogs/2007/09/14/pivots-with-dynamic-columns-in-sql-server-2005/
Hope this will help

SQL query using (self?) Join

I have a problem with a question I don't fully understand. Was wondering if anyone could help me with it, Or at least help me understand.
Lets say we have a table 'Jobs' with 2 columns job numbers 'jobnum', and employee numbers 'empnum'
Table: Jobs
---------------------------------------
| jobnum | empnum |
---------------------------------------
| 125 | 4785 |
| 100 | 4200 |
| 305 | 4001 |
| 125 | 4224 |
| 102 | 4840 |
| 100 | 4224 |
| 107 | 4534 |
| 255 | 4200 |
| 208 | 4224 |
| 301 | 4785 |
---------------------------------------
I like the job that was done at a certain work site, lets take jobnum '125', and want to know the other jobnums of the same employees. It shows that two people worked on jobnum 125. '4224' and '4785'. How would I write a SQL query that would output the jobnums of the same people that did job '125'. I am supposed to use Join query and cannot use sub-query
I understand how I would do it using a sub-query but don't know how I would going about it using a Join. I am assuming I would do a self join? Perhaps I don't fully understand Joins =/
Using Join:
Select
j1.jobnum,
j1.empnum
From jobs j1
Join jobs j2
On j1.empnum = j2.empnum
Where j2.jobnum = 125
The query says "Give me all the records from jobs (j1) that have the same empnum as any record in jobs (j2) which has a jobnum of 125. That's the self-join that you're looking for.
This is a generic solution
SELECT T1.*
JOBS T1
INNER JOIN JOBS T2
ON( T1.jobnum=T2.jobnum AND T1.empnum<> T2.empnum)