data from two tables and one show

2019-09-15 10:12发布

问题:

I have two similar table in database, for example:

news1:

id | title | body|
1  | aaa   | aaa |
2  | ggg   | bbb |
2  | xxx   | ccc |

and news2:

id | title | body | photo |
1  | BBB   | 111  | 111
2  | RRR   | 222  | 222
3  | EEE   | 333  | 333

how can i get data from two tables and show in template for example order by title?

title | body | photo
aaa   | aaa
BBB   | 111  | 111
EEE   | 333  | 333
ggg   | ggg
RRR   | 222  |222
xxx   | xxx

?

回答1:

use Union

SELECT *
  FROM news1 n1
UNION ALL
SELECT *
  FROM news2 n2

UNION ALL will be faster, but won't remove duplicates if they exist. Use UNION if you want duplicates removed. Joining two similar tables in MySQL