开发者

Join two tables with different number of rows in MySQL

开发者 https://www.devze.com 2023-03-11 12:14 出处:网络
I have two tables: --------- |dogs| --------- |item_1 | --------- --------- |cats| --------- |item_1 | |item_2 |

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消