0

我从来没有弄清楚关于 SQL 子查询的几个语法问题。主要我感兴趣的是在父查询中放置子查询是否有效。

这是一个引发错误的示例:

SELECT 
  sum(votes.vote) AS sum, 
  votes.vote IS NOT NULL AS did_i_vote, 
  purchase_id, subject, full_name 
FROM (
  SELECT vote FROM votes 
  where votes.acct_id=3 AND 
    votes.column_name='purchase_id'
) votes  
RIGHT JOIN items_purchased 
  ON votes.parent_id=items_purchased.purchase_id  
JOIN accounts 
  ON items_purchased.purchaser_account_id=accounts.acct_id   
JOIN items 
  ON items_purchased.item_id=items.folder_id   
WHERE purchase_id='2' 
GROUP BY items_purchased.purchase_id

如何使这个查询工作?

4

2 回答 2

2

零件有一处错误GROUP BY

在 中SELECT,您只能在GROUP BY不存在的列的和聚合函数中显示列。


检查信息!

于 2012-05-03T16:07:58.300 回答
1

subquery必须选择column之后要引用的每一个。

SELECT 
  sum(votes.vote) AS sum, 
  votes.vote IS NOT NULL AS did_i_vote, 
  purchase_id, subject, full_name 
FROM (
  SELECT vote, parent_id FROM votes 
  where votes.acct_id=3 AND 
    votes.column_name='purchase_id'
) votes  
RIGHT JOIN items_purchased 
  ON votes.parent_id=items_purchased.purchase_id  
JOIN accounts 
  ON items_purchased.purchaser_account_id=accounts.acct_id   
JOIN items 
  ON items_purchased.item_id=items.folder_id   
WHERE purchase_id='2' 
GROUP BY items_purchased.purchase_id

是我假设的(注意我在子查询中选择vote和)parent_id

于 2012-05-03T16:06:54.117 回答