简体   繁体   中英

How to create a view in MySQL with unrelated tables

I have 4 different tables in MySQL, without matching criteria and foreign keys, and for some special need and better performing I need to regroup all those data in a single MySQL VIEW.

The structure of those tables are similar and like this (but remember even the same fields are not connected):

table1 (id, name, date, price, description)
table2 (id, type, date, price, note)
table3 (id, name, date, price, note)
table4 (id, name, date, price, description)

Is there a way to create a view with 4 columns grouping the data of the previous tables? I can't use a join because like I said before there is no connection between those data, that's why I tought about views. I can't even create a single table containing all those fields because this would be mean for the rest of my application.

I need to create 4 fields like this: date, name, price, description. For example price will contain the prices of each of table1..to table4.

If this tuple <name, date, price, description> is allowed to be duplicate then you can use UNION ALL and if you don't want to allow duplicates in your view then use UNION instead of UNION ALL .

DROP VIEW IF EXISTS combinedTableView ;

CREATE VIEW combinedTableView AS 

SELECT 
`name`,
`date`,
price,
description
FROM table1

UNION ALL

SELECT 
`name`,
`date`,
price,
description
FROM table2

UNION ALL

SELECT 
`name`,
`date`,
price,
description
FROM table3

UNION ALL

SELECT 
`name`,
`date`,
price,
description
FROM table4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM