我从未想过有关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
如何使此查询有效?
答案 0 :(得分:2)
答案 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
我会假设(注意我在子查询中选择vote
和parent_id
)