我正在尝试执行此查询,但显示错误
select
order_id,
product_id
from (select
order_id,
product_id,
count(*) over(partition by order_id, product_id) as dc
from order_items
)
where dc > 1 ;
我得到的错误是
您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以获得正确的语法,使用'(order by order_id,product_id)作为来自order_items的dc附近),其中dc>第1行1'
答案 0 :(得分:2)
不幸的是,MySQL仍然不支持窗口函数。因此OVER
子句在MySQL中不起作用。
您可以使用子查询或使用用户(会话)变量来模拟它。
从order_items
中选择实际行的一种方法,其中每个订单多次出现相同的product_id
select i.*,
(
select count(*)
from order_items
where order_id = i.order_id
and product_id = i.product_id
) as dc
from order_items i
having dc > 1
或加入
select i.*, dc
from
(
select order_id, product_id, count(*) dc
from order_items
group by order_id, product_id
having dc > 1
) q join order_items i
on q.order_id = i.order_id
and q.product_id = i.product_id;
如果另一方面,您需要仅 order_id和product_id以及此类行的总计数
select order_id, product_id, count(*) dc
from order_items
group by order_id, product_id
having dc > 1;
这是 SQLFiddle 演示
答案 1 :(得分:0)
select
order_id,
product_id
from order_items
group by order_id, product_id
having count(*)>1