Chris Quibell
Chris Quibell

Reputation: 339

I need to combine two results from a SQL select query

I Have two Select queries that get results for two tables with the same column names.

SELECT 
    labels.langjrd,
    labels.id,
    labels.lcphrase 
FROM 
    labels 
WHERE 
    labels.langjrd LIKE 'FRE%'
;

and

SELECT
    labels.langjrd,
    labels.id,
    labels.lcphrase 
FROM 
    labels 
WHERE 
    labels.langjrd LIKE 'ENG%'
; 

When I run the query I want to put all the results into one table. I read about union query but when I tried it, it didn’t work. I don't want to overwrite all the duplicate data I just want to have the second select results be added to the bottom of the first select results.

Upvotes: 3

Views: 684

Answers (1)

GolezTrol
GolezTrol

Reputation: 116100

With UNION ALL you can combine results from two queries like this:

SELECT 
  labels.langjrd,labels.id,labels.lcphrase 
FROM 
  labels 
WHERE 
  labels.langjrd LIKE  'FRE%'
UNION ALL
SELECT 
  labels.langjrd,labels.id,labels.lcphrase 
FROM 
  labels 
WHERE 
   labels.langjrd LIKE 'ENG%';

You read about UNION which does a similar thing, but it filters out duplicate results. So it's similar as UNION ALL, but not the same.

But since you are actually querying the exact same columns from the same table, you can just put the two conditions in the where clause and split them using or. That way you will get all records that match either of the conditions.

SELECT 
  labels.langjrd,labels.id,labels.lcphrase 
FROM 
  labels 
WHERE 
  labels.langjrd LIKE 'FRE%' OR
  labels.langjrd LIKE 'ENG%';

Upvotes: 11

Related Questions