mysql - 无法执行 sql 查询

标签 mysql sql

我正在尝试执行此查询,但它显示错误

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  ;

我遇到的错误是

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(partition by order_id, product_id) as dc from order_items) where dc > 1' at line 1

最佳答案

不幸的是,MySQL 仍然不支持窗口函数。因此 OVER 子句在 MySQL 中不起作用。

您可以使用子查询或使用用户( session )变量来模拟它。

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 演示

关于mysql - 无法执行 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21250025/

相关文章:

php - 在 Laravel 中为现有数据库中的存储过程、函数和事件创建迁移

php - 在 codeigniter 中使用两个输入字段进行搜索

java - Spring Boot 连接到 mysql docker

mysql - 按术语进行标签搜索包括和排除

java - Hibernate中连续命名参数问题(Spring HibernateTemplate)

mysql - SQL 中的多个 LEFT JOIN 运行缓慢。我该如何优化它?

mysqldump Windows 未知选项 '--no beep'

PHP PDO 数据库备份类

php - 根据数组值使用Where子句查询数据库

mysql - SQL查询以通过连接获取与最大值对应的行