简体   繁体   中英

Join two tables with different number of rows in MySQL

I have two tables:

---------
|dogs   |
---------
|item_1 |
|       |
|       |
|       |
---------

---------
|cats   |
---------
|item_1 |
|item_2 |
|item_3 |
|item_4 |
---------

so I want to join the tables something like this:

------------------
|dogs   | cats   |
------------------
|item_1 | item1  |
|NULL   | item2  |
|NULL   | item3  |
|NULL   | item4  |
------------------

I use a condition in the second table, but if nothing is found I still want to get that single result from the first table something like this:

------------------
|dogs   | cats   |
------------------
|item_1 | NULL   |
------------------

The tables don't have ID fields, but I can also add an ID to make a relation between the items.

I already tried different solutions, but I can't get to keep the single result from the first table if nothing was found in the second table when using a condition (I get 0 rows), or I get repeated the item1 in the first table when I actually need Nulls.

select *
from dogs left outer join cats

This will give you all dogs and any matching cats. This means that the Cat columns could be null, but the dog columns can not. Is this what you are looking for?

When you add id's to both tables, you can use SQL left join to match all the data from the right table to the left table.

From W3Schools:

The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).

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