我很难过这个。简而言之,我有3个表:Product,Ranging,Account。测距是中间表,它是产品和帐户之间的链接。
e.g。范围记录链接到1个帐户和1个产品。产品可以有很多范围,因此账户也可以。
我最终想要的是3列:1 =产品名称,2 =帐户名称,3 =测距(存在(是/否)。这很容易,但是我要显示的是棘手的一点每个产品下的每个帐户。
即。如果我有PROD 1,2和3以及账户A,B和C.我想看看:
帐户,产品和范围都有链接的ID(PK,FK等)
我尝试过使用内连接的交叉连接无济于事。 感谢帮助!
答案 0 :(得分:0)
你在找这个吗?
SELECT q.product_name, q.account_name,
CASE WHEN r.product_id IS NULL THEN 'no' ELSE 'yes' END status
FROM
(
SELECT product_id, product_name, account_id, account_name
FROM product p CROSS JOIN account a
) q LEFT JOIN ranging r
ON q.product_id = r.product_id
AND q.account_id = r.account_id
ORDER BY q.product_name, q.account_name
示例输出:
| PRODUCT_NAME | ACCOUNT_NAME | STATUS | ---------------------------------------- | Product 1 | Account A | yes | | Product 1 | Account B | no | | Product 1 | Account C | yes | | Product 2 | Account A | yes | | Product 2 | Account B | no | | Product 2 | Account C | no | | Product 3 | Account A | no | | Product 3 | Account B | no | | Product 3 | Account C | no |
这是 SQLFiddle 演示
答案 1 :(得分:0)
您需要cross join才能执行此操作:
select
p.name as product_name,
a.name as account_name,
case when r.product_id is not null then 'yes' else 'no' end as Ranging
from product as p
cross join account as a
left outer join ranging as r on r.product_id = p.id and r.account_id = a.id
order by p.name, a.name