Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mysql Union All on GORM?

Tags:

mysql

go

go-gorm

I'm working with complicated structure database, and after update we start using GORM so I need to transform this script using GORM.

query := `
  SELECT * FROM foo
  UNION ALL
  SELECT * FROM bar WHERE id=1`
rows, err := db.Query(query)

What is the best way to do it?

like image 249
Muslihudin Avatar asked Apr 21 '21 07:04

Muslihudin


People also ask

Can we use UNION all in MySQL?

The MySQL UNION ALL operator is used to combine the result sets of 2 or more SELECT statements. It returns all rows from the query and it does not remove duplicate rows between the various SELECT statements.

What is UNION in MySQL with example?

The UNION operator is used to combine the result-set of two or more SELECT statements. Every SELECT statement within UNION must have the same number of columns. The columns must also have similar data types. The columns in every SELECT statement must also be in the same order.

How do I find a UNION in MySQL?

The following are the syntax of Union operator in MySQL: SELECT column_list FROM table1. UNION ALL.

What is UNION clause and UNION all clause in MySQL?

The MySQL UNION operator performs to give the distinctive values of set in the result after the union of the result rows of SELECT statements whereas the MySQL UNION ALL operator allows the union producing the result set from SELECT statements having replica values in the records fetched from the database tables where ...


1 Answers

Note that gorm doesn't support UNION directly, you need to use db.Raw to do UNIONs:

db.Raw("? UNION ?",
    db.Select("*").Model(&Foo{}),
    db.Select("*").Model(&Bar{}),
).Scan(&union)

the above will produce something like the following:

SELECT * FROM "foos"
WHERE "foos"."deleted_at" IS NULL
UNION
SELECT * FROM "bars"
WHERE "bars"."deleted_at" IS NULL
like image 100
mkopriva Avatar answered Oct 21 '22 08:10

mkopriva