mysql 带Case条件的内联接[已关闭]

wb1gzix0  于 2023-03-07  发布在  Mysql
关注(0)|答案(1)|浏览(133)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

5小时前关门了。
Improve this question
我有三个表,分别命名为A、B和C。
表A具有以下模式。
(EMAIL,FIRST_NAME,LAST_NAME)
表B具有以下模式。
(EMAIL,PRODUCT_NAME,PRODUCT_NUMBER).
表C具有以下模式。
(EMAIL,PRODUCT_NAME,PRODUCT_NUMBER).
我试图构造一个SQL查询,可以给予我如下详细信息:
从表A中,获取表B中与表C WHERE中的记录匹配的所有记录的名和姓

B.EMAIL = C.EMAIL and B.PRODUCT_NAME = C.PRODUCT_NAME AND B.PRODUCT_NUMBER = C.PRODUCT_NUMBER

最终表格记录应如下所示,并有一个以“结果”命名的附加列。

(A.FIRST_NAME,A.LAST_NAME,B.PRODUCT_NAME,B.PRODUCT_NUMBER,RESULT)

应根据以下条件确定结果值:

  • 如果记录同时出现在表B和表C中(B.电子邮件= C.电子邮件和B.产品名称= C.产品名称和B.产品编号= C.产品编号),则已收到
  • 如果记录出现在表C中,但未出现在表B中(匹配B.email=C.email),则收到
  • 如果记录出现在表B中,但未出现在表C中(匹配B.email=C.email),则未收到

有谁能建议一种构造这个查询的方法吗?我对sql相当陌生。
我尝试了下面的查询,但我没有得到它的权利.

SELECT DISTINCT 
 B.PRODUCT_NAME,B.PRODUCT_NUMBER,A.FIRST_NAME,A.LAST_NAME,
'Received' as RESULT 
FROM B 
INNER JOIN C on B.EMAIL = C.EMAIL  
and B.PRODUCT_NAME = C.PRODUCT_NAME 
and B.PRODUCT_NUMBER = C.PRODUCT_NUMBER WHERE A.EMAIL = C.EMAIL
UNION
(SELECT DISTINCT 
B.PRODUCT_NAME,B.PRODUCT_NUMBER,A.FIRST_NAME,A.LAST_NAME,
'NOT Received' as RESULT 
FROM B 
INNER JOIN C 
on B.EMAIL = C.EMAIL and B.PRODUCT_NAME != C.PRODUCT_NAME 
and B.PRODUCT_NUMBER != C.PRODUCT_NUMBER WHERE A.EMAIL = C.EMAIL)
nukf8bse

nukf8bse1#

您要查找的查询如下所示:

with

t1 as (
select
 b.email,
 b.product_name,
 b.product_number,
 (case
  when c.product_name is null then 'not received'
  when c.product_name is not null then 'received'
  end) as result
from
 b
 left join c on b.email = c.email and b.product_name = c.product_name
),

t2 as (
select
 c.email,
 c.product_name,
 c.product_number,
 'received' as result
from
 c
 left join b on c.email = b.email and c.product_name = b.product_name
where
 b.product_name is null
),

orders as (
select * from t1
union
select * from t2
),

result as (
select
 clients.first_name,
 clients.last_name, 
 orders.*
from
 orders
 left join a as clients on clients.email = orders.email 
)

select * from result

相关问题