简体   繁体   English

如何在MYSQL中联接多个没有NULL值的表?

[英]How to Join multiple table without NULL value in MYSQL?

I need help with query: There are 3 tables named: 我需要查询方面的帮助:有3个表,它们名为:

 1. comments (fields: id, uacc_id_fk , comment)
             (values: 1, 5, my comment)
             (values:2, 10, hi im fine)

 2. dogowner_profile (fields: uacc_id_fk,dpro_name,dpro_image)
                     (values:5,Jones,Jones.jpg)


 3. doglover_profile (fields:uacc_id_fk,dlpro_name,dlpro_image)
                     (values:10,jeeva,jeeva.jpg)

I need result like: 我需要这样的结果:

(fields: uacc_id_fk , comment , name , image)
(values: 5, my comment, jones, jones.jpg)
(values: 10, hi i'm Fine, jeeva, jeeva.jpg)

But the output I am getting now is like: 但是我现在得到的输出是:

The query I used here is: 我在这里使用的查询是:

  SELECT comments . * 
       , dpro_name AS Name
       , dlpro_name AS Name
       , dpro_image AS Image
       , dlpro_image AS Image
    FROM comments
    LEFT 
    JOIN dogowner_profile 
      ON comments.uacc_id_fk = dogowner_profile.dpro_uacc_id_fk
    LEFT 
    JOIN doglover_profile 
      ON comments.uacc_id_fk = doglover_profile.dlpro_uacc_id_fk

But the result I got here is: 但是我得到的结果是:

(fields:id,uacc_id_fk,comment,name,name,image,image)
(values:1,5, my comment,jones,NULL,jones.jpg,NULL)
(values:2,10,hi i'm Fine,NULL,jeeva,NULL,jeeva.jpg)

I think these SQL useful to you. 我认为这些SQL对您有用。

       SELECT comments . uacc_id_fk  ,comments.comment , dpro_name AS Name,dpro_image AS Image
       FROM    comments
      JOIN dogowner_profile ON comments.uacc_id_fk = dogowner_profile.dpro_uacc_id_fk

    Union   

        SELECT comments . uacc_id_fk  ,comments.comment , dlpro_name AS Name,dlpro_image AS Image
        FROM    comments
       JOIN doglover_profile ON comments.uacc_id_fk = doglover_profile.dlpro_uacc_id_fk`

Thank you. 谢谢。

If you have multiple columns that might contain data or might be NULL , and you want to find the first non- NULL one, just use COALESCE : 如果您有多个可能包含数据或可能NULL ,并且想要查找第一个非NULL ,则只需使用COALESCE

SELECT
    comments.*,
    COALESCE(dpro_name, dlpro_name) AS Name,
    COALESCE(dpro_image, dlpro_image) AS Image
 FROM
     comments
     LEFT JOIN dogowner_profile ON
         comments.uacc_id_fk = dogowner_profile.dpro_uacc_id_fk
     LEFT JOIN doglover_profile ON
         comments.uacc_id_fk = doglover_profile.dlpro_uacc_id_fk;

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

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