简体   繁体   English

如果找不到匹配项,如何附加列数据?

[英]How to append column data if no match has found?

I have table1 and table2 as following 我有table1和table2如下

Table1 表格1

first_name | last_name | t1_id

Table2 表2

T2_id | color | length

Table1 may have an id value which doesn't exist in Table2 id, however it may exist sometimes. 表1可能具有表2中不存在的id值,但有时可能存在。 I want to write a query that gives the following result: First_name | 我想编写一个给出以下结果的查询:First_name | last_name | last_name | t1_id | t1_id | color | 颜色| length Where in case if the id value doesn't exist in table2 the result should be like: length如果table2中不存在id值,结果应该是:

First_name | last_name | t1_id | color | length
-----------------------------------------------
Johan      | Mike      | 33    |   -   |   -

My try: 我的尝试:

SELECT first_name,
       last_name,
       t1_id,
       color,
       length
FROM Table1, Table2
WHERE t1_id = t2_id

But this show the result when the value of t1_id only exists in t2_id . 但这显示了当t1_id的值仅存在于t2_id时的结果。

Use LEFT join to get all rows from first table even if their associations are not present in second table 使用LEFT join从第一个表中获取所有行,即使它们的关联在第二个表中不存在

SELECT first_name,
       last_name,
       t1_id,
       color,
       length
FROM Table1
LEFT JOIN Table2 ON t1_id = t2_id

You could use COALESCE(column,'-') to show - if column is null 您可以使用COALESCE(column,'-')来显示-如果列为null

SELECT first_name,
       last_name,
       t1_id,
       COALESCE(color,'-'),
       COALESCE(length,'-')
FROM Table1
LEFT JOIN Table2 ON t1_id = t2_id

Use Left Join 使用左连接

SELECT first_name,
       last_name,
       t1_id,
       color,
       length
FROM Table1
LEFT JOIN Table2 ON t1_id = t2_id

you can use mysql left join join in this case if right table data not found then null 在这种情况下,如果找不到正确的表数据,则可以使用mysql 左连接连接

SELECT t1.first_name,
       t1.last_name,
       t1.t1_id,
       t2.color,
       t2.length
FROM table1  t1
LEFT JOIN table2 t2 
ON t1.t1_id = t2.t2_id;

in this sql i use alias but if you do not want it then 在这个SQL我使用别名,但如果你不想要它

SELECT first_name,
       last_name,
       t1_id,
       color,
       length
    FROM table1  
    LEFT JOIN table2  
    ON t1_id = t2_id;

for more information 欲获得更多信息

https://dev.mysql.com/doc/refman/5.7/en/left-join-optimization.html https://dev.mysql.com/doc/refman/5.7/en/left-join-optimization.html

You should make use of LEFT JOIN 你应该使用LEFT JOIN

SELECT *
FROM Table1 LEFT JOIN Table2
ON t1_id = t2_id

Try this one : 试试这个:

SELECT first_name,
       last_name,
       t1_id,
       color,
       length
FROM Table1, Table2
WHERE t1_id = t2_id(+)

Regards, Damodar 此致,达莫达尔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM