有效的MySQL子查询语法和位置

时间:2012-05-03 16:04:16

标签: mysql sql syntax subquery

我从未想过有关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

如何使此查询有效?

2 个答案:

答案 0 :(得分:2)

GROUP BY部分有一个错误!

SELECT中,您只能在GROUP BY中显示列,并且不包含不存在的列的功能。


检查THIS信息!

答案 1 :(得分: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

我会假设(注意我在子查询中选择voteparent_id