我想在MySQL中使用join和or条件将3个表与一个公共列连接在一起

问题描述

我有3个表-个人资料,产品,服务

个人资料具有一个字段document_id,供应商名称,该字段与产品(字段-作者)和服务(字段-作者)链接

个人资料:与产品链接的文档ID很少,与服务链接的文档ID很少,两者都链接的ID很少,而与服务链接的ID很少。

我想要输出

____________________________________
vendorName  Product      Service
ABC         Fruits         -
            vegetables     -
            Cereals      Selling
DEF           -            -
GHI           -         Plumbing
______________________________________

我写了以下查询,但这是不正确的:

select disTINCT Profiles.document_id as Document_ID,JSON_EXTRACT_SCALAR(Product.Data,'$.author'),JSON_EXTRACT_SCALAR(Services.Data,ifnull(concat(UPPER(JSON_EXTRACT_SCALAR(Profiles.DATA,'$.firstName')),' ',upper(JSON_EXTRACT_SCALAR(Profiles.DATA,'$.lastName'))),"-")  AS vendorName,ifnull(UPPER(JSON_EXTRACT_SCALAR(Product.DATA,'$.category')),"-") as productCategory,ifnull(UPPER(JSON_EXTRACT_SCALAR(Services.DATA,"-") as ServiceCategory
FROM
`roque-prod.profiles.profiles_raw_latest` as Profiles
JOIN
`roque-prod.roqueprod.roque_raw_latest` as Product
ON
Profiles.document_id = JSON_EXTRACT_SCALAR(Product.Data,'$.author')
OR
JOIN 
services.services_raw_latest as Services
ON
Profiles.document_id = JSON_EXTRACT_SCALAR(Services.Data,'$.author')

我遇到以下错误

运行查询时出错:语法错误:[17:1]处出现意外的关键字JOIN

我也尝试使用union,但是它不能正确地达到我的目的。使用union,所有产品和服务都合并到一个字段中,这意味着所有产品记录都与服务结合在一起。但是我希望这些字段应该在不同的列中(请检查提到的输出)。

--> For Union I used the following query
select Profiles.document_id as Document_ID,FROM
`roque-prod.profiles.profiles_raw_latest` as Profiles
JOIN
`roque-prod.roqueprod.roque_raw_latest` as Product
ON
Profiles.document_id = JSON_EXTRACT_SCALAR(Product.Data,'$.author')

UNION all

select Profiles.document_id as Document_ID,"-") as ServiceCategory
FROM
`roque-prod.profiles.profiles_raw_latest` as Profiles
JOIN 
services.services_raw_latest as Services
ON
Profiles.document_id = JSON_EXTRACT_SCALAR(Services.Data,'$.author')

解决方法

要获取不同列中的并集字段,请在每个子查询中为来自其他子查询的数据放置空的“虚拟”值。总体结构应为:

SELECT * FROM (
    SELECT common_col1,common_col2,...,table1_col1,table1_col2,'-' AS table2_col1,'-' AS table2_col2,...
    FROM table1
    
    UNION ALL
    
    SELECT common_col1,'=' AS table1_col1,'-' AS table1_col2,table2_col1,table2_col2,...
    FROM table2
) AS x
ORDER BY common_col1,...