我的目标是删除重复的productID
,使查询选择的记录比没有clientID
的记录更好。
这个想法是将文件(如手册)链接到产品。但是,当文件也链接到客户端时,它应优先于全局链接文件,因为该文件仅适用于此特定客户端。
我不确定这是否可行,表格如下:
client_products
| client | product |
产品
| ID | name |
product_specifications
| filepath | product | client |
现在,这是我到目前为止所做的:
SELECT products.*, ps.specification, cp.client
FROM products
LEFT JOIN product_specifications ps on ps.product = products.ID
RIGHT JOIN client_products cp ON cp.product = products.ID
WHERE cp.client = 1
AND products.ID = cp.product
ORDER BY products.name
显然,我正在使用一些连接进行基本选择查询。我正在通过products.ID
对其进行分组,以确保我没有将产品返回两次,但这并不能保证我将获得特定客户端的链接规范文件,对吧?任何想法将不胜感激!
示例结果:
我得到了什么(没有GROUP BY
)
| ID | specification | client |
| 1 | 1 | 1 |
| 1 | 1 | NULL |
| 2 | 3 | NULL |
当客户端列不为空时我想得到的是:
| ID | specification | client |
| 1 | 1 | 1 |
| 2 | 3 | NULL |
答案 0 :(得分:1)
我已经解决了类似的后备问题here。 "技巧"是使用LEFT JOIN来查看是否存在客户特定文件:
select p.*, ps.*
from client_products cp
join products p on p.ID = cp.product
left join product_specifications ps
on ps.product = p.ID
and (ps.client = 1 or ps.client IS NULL)
left join product_specifications ps1
on ps1.product = p.ID
and ps1.client = 1
and ps.client IS NULL
where cp.client = 1
and ps1.client IS NULL
http://sqlfiddle.com/#!9/d9d705/29
如果您只需要product_specifications
表中的一列,您也可以尝试这一列:
select p.*, coalesce(ps.specification, ps1.specification) as specification
from client_products cp
join products p on p.ID = cp.product
left join product_specifications ps
on ps.product = p.ID
and ps.client = 1
left join product_specifications ps1
on ps1.product = p.ID
and ps1.client IS NULL
where cp.client = 1
http://sqlfiddle.com/#!9/d9d705/34
您加入product_specifications
表两次。一次为client = 1
,一次为client IS NULL
。使用COALESCE()
只有在第一个没有退出时才选择第二个。
答案 1 :(得分:0)
我认为您的问题的核心可以通过以下方式解决(我可能稍微修改了列名)......
SELECT x.*
FROM product_specifications x
JOIN
( SELECT product_id
, MAX(client_id) client_id
FROM product_specifications
GROUP
BY product_id
) y
ON y.product_id = x.product_id
AND (y.client_id = x.client_id OR y.client_id IS NULL);