【问题标题】:SQL QUERY ON MULTIPLES TABLES多表上的 SQL 查询
【发布时间】:2018-01-12 01:23:16
【问题描述】:

我是 Pure Sql 的新手,我想把它写成 Query

select items.* 
from items 
LEFT OUTER JOIN 
    (select sum(purchase_details.quantity) as total 
    from purchase_details 
    where (purchase_details.item_id=items.id)  
GROUP BY purchase_details.item_id) ABC 

但这会报错

 You have an error in your SQL syntax; check the manual that corresponds to 
    your MariaDB server version for the right syntax to use near 'LIMIT 0, 25' 
    at line 1

我不知道为什么它不起作用

【问题讨论】:

  • 您的查询没有LIMIT 关键字(在错误消息中提到),您可以发布完整的查询吗?
  • 该错误与您的代码不符。重写你的问题,或者你的代码,或者你的错误……或者一切
  • 你不指定要加入的字段是整个select语句吗?此外,您的连接子查询中只有 sum 字段吗?也许您需要添加 Item_ID?

标签: php mysql apache phpmyadmin


【解决方案1】:

这里的语法错误是您的left join 需要一个on 子句。但潜在的概念问题是不同的:您不能 join 使用 依赖子查询

您可以像这样修复您的查询:

select items.* 
from items 
LEFT OUTER JOIN (
  select item_id, sum(purchase_details.quantity) as total
  from purchase_details 
  GROUP BY purchase_details.item_id
) ABC on ABC.item_id = items.id;

这将您的内部where-条件(这将取决于items.id,这是不允许的,因为它超出了范围)移动到on-子句。因此item_id 也被添加到内部select 中(因为它需要在外部)。

另一种写法是

select items.*, 
   (select sum(purchase_details.quantity) 
    from purchase_details 
    where purchase_details.item_id=items.id) as total
from items;

这里有一个依赖子查询:内部where-子句依赖于外部items.id。您不再需要group by,因为where-条件已经只使用了该项目的行。 (无论如何,在这种情况下,您也最多只能返回一行。)

这两个查询是等效的,并且可以(如果优化器发现该执行计划)在内部实际上以完全相同的方式执行(不过,只要您提供适当的索引,您不必太在意)。

因此,在您的情况下,您可以同时使用两者(也许检查哪个更快);如果您想获得该项目的其他信息,您应该更喜欢left join-version,例如使用

...
LEFT OUTER JOIN (
  select item_id, 
    sum(purchase_details.quantity) as total,
    count(purchase_details.item_id) as cnt,
    max(purchase_details.quantity) as max_quantity_per_order,
    max(purchase_details.date) as latest_order,
    ...
  from purchase_details 
  GROUP BY purchase_details.item_id
) ABC on ABC.item_id = items.id;

【讨论】:

    猜你喜欢
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多