问题
On my webserver there is a database with following two tables:
tbl_Friend tbl_Colleague
| id | Name | First name | Place | | id | Name | First name | Place |
---------------------------------- ----------------------------------
| 1 | XXXX | XXXXXXXXXX | 1 | | 1 | AAAA | AAAAAAAAAA | 1 |
| 2 | YYYY | YYYYYYYYYY | 2 | | 2 | BBBB | BBBBBBBBBB | 3 |
| 3 | ZZZZ | ZZZZZZZZZZ | 1 | | 3 | CCCC | CCCCCCCCCC | 4 |
Now I want to fetch all Persons from tbl_Friend
and tbl_Colleague
who live in place 1
. For that I have to the data from both tables and here is my problem: How can I fetch data from two different tables in only one query? My result should look like this:
| id | Name | First name | Place |
----------------------------------
| 1 | XXXX | XXXXXXXXXX | 1 |
| 1 | AAAA | AAAAAAAAAA | 1 |
| 3 | ZZZZ | ZZZZZZZZZZ | 1 |
Can I use something like FROM tbl_Friend | tbl_Colleague
or something else? Or do I have to use a Join for this?
回答1:
Try this:
SELECT id, Name, First name, Place FROM tbl_Friend
WHERE Place= 1
UNION ALL
SELECT id, Name, First name, Place FROM tbl_Colleague
WHERE Place= 1
回答2:
try this:
select * from tbl_friend a, tbl_colleague b where a.place = b.place and place like '1';
来源:https://stackoverflow.com/questions/23281450/fetch-data-from-two-different-tables-in-one-query