Alex N
Alex N

Reputation: 1121

how to combine the two queries sql?

Good day.

I have two sql query:

First:

SELECT name FROM 
TableOne
WHERE city='3452' AND firm='49581' AND service='2'
Group by name

Second:

SELECT name FROM 
TableTwo
WHERE city='3452' AND firm='49581' AND service='2'
Group by name

Tell me please how to combine the two queries sql and select all name (with group by name) from two tables ?

Upvotes: 0

Views: 183

Answers (4)

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52157

Well, "combine" can mean a lot of things, but I'm guessing you want something like this:

SELECT name
FROM (
    SELECT name, city, firm, service FROM TableOne
    UNION ALL
    SELECT name, city, firm, service FROM TableTwo
) Q
WHERE city='3452' AND firm='49581' AND service='2'
GROUP BY name

There is no need to use UNION (without ALL), since GROUP BY will remove the duplicates anyway.

BTW, are all these fields used in the WHERE clause really strings? If not, you'd want to remove single quotes as appropriate. It's a bit suspicious that you are using string literals that contain only numbers.

Upvotes: 1

Marichyasana
Marichyasana

Reputation: 3154

I believe this syntax is a little simpler and thus easier to maintain. The comma in line two does a join.

SELECT name FROM 
TableOne, TableTwo
WHERE city='3452' AND firm='49581' AND service='2'
Group by name

Upvotes: 0

İsmet Alkan
İsmet Alkan

Reputation: 5447

Just use UNION operator between two queries. According to answer in this similar question:

You may be looking at using a UNION in you query:

Select * from a UNION Select * from b Note:

It is better practice to qualify your column names instead of using the * reference. This would also make the query still useful if your two tables underwent schema changes but you still wanted to pull back all the data the two tables had in common.

Union will rule out same objects. To avoid that you can use UNION ALL instead.

Upvotes: 1

Steven Wexler
Steven Wexler

Reputation: 17329

You can use UNION ALL http://sqltutorials.blogspot.com/2007/06/sql-union-all.html

SELECT name
FROM (
    SELECT name 
    FROM TableOne
    WHERE city='3452' AND firm='49581' AND service='2'
    UNION ALL
    SELECT name 
    FROM TableTwo
    WHERE city='3452' AND firm='49581' AND service='2' ) x
GROUP BY name

Upvotes: 1

Related Questions