我有一个包含客户记录的表customershipments
。列 Item
和 OrderNumber
。我想查看一整套,其中 Item
位于多个唯一的 OrderNumber
上。
SELECT
distinct
cs.item
,cs.ordernumber
FROM
customershipments cs
JOIN
customershipments cs2
ON cs.item = cs2.item
AND cs.ordernumber <> cs2.ordernumber
WHERE
AND cs.cdate > NOW() - INTERVAL 1 WEEK
AND cs.isactive = 1
AND cs.item <>''
AND cs.hostcompany_id =19
ORDER BY
cs.item, cs.ordernumber
这确实识别了我想要的items
,但只返回第一个OrderNumber
,而不返回第二个。除非item
有两个以上的OrderNumber
,否则它会向我显示所有情况。我不明白为什么。就像我说的,这足以指出我需要管理的记录(基于项目),但它没有向我显示订单号的详尽列表。
最佳答案
您不需要自加入。只需使用聚合即可。要获取项目列表:
select item
from customershipments cs
where cs.cdate > NOW() - INTERVAL 1 WEEK and
cs.isactive = 1 and
cs.item <> '' and
cs.hostcompany_id =19
group by item
having count(distinct ordernumber) > 1;
然后您可以加入此返回以获取订单列表:
select cs.*
from (select item
from customershipments cs
where cs.cdate > NOW() - INTERVAL 1 WEEK and
cs.isactive = 1 and
cs.item <> '' and
cs.hostcompany_id =19
group by item
having count(distinct ordernumber) > 1
) i join
customershipments cs
on cs.item = i.item;
或者,在一行中获取订单号列表:
select item, group_concat(ordernumber)
from customershipments cs
where cs.cdate > NOW() - INTERVAL 1 WEEK and
cs.isactive = 1 and
cs.item <> '' and
cs.hostcompany_id =19
group by item
having count(*) > 1;
关于mysql - 无法查看全套 : Self Join - Compare where Column1 = and Column2 <>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28510852/