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?
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.
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.
The following are the syntax of Union operator in MySQL: SELECT column_list FROM table1. UNION ALL.
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 ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With