简体   繁体   中英

In MySQL, how do I select * from two different tables?

I have two separate tables on MySQL, and I want to make a query where I select * from both of them and I want to order them by id (or date). The problem is the id's will conflict, since there will be two articles with the same id (one from each table).

Is there a way where I can display all the articles of each table in one single query?

Edit:

They don't have the same number of columns. However, I will be choosing the same columns of each of them. So I'd be selecting "id, map, title, summary, image, date, publish" from both table1 and table2. (because both of the tables have those exact same columns).

Then I want to display on a single web page all the articles from both table1 and table2. In the exact same grid.

Is this even possible or do I need to merge both tables in MySQL?

If the 2 tables have the same number of columns and the data types of the corresponding columns are the same, then you can use UNION ALL:

SELECT * FROM table1
UNION ALL
SELECT * FROM table2
ORDER BY id

If you also want to distinguish the rows so you know from which table they originate, you can create a dummy 1st column for each of them like this:

SELECT '1' fromtable, * FROM table1
UNION ALL
SELECT '2' fromtable, * FROM table2
ORDER BY id

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