1

我想计算每个项目的购买次数,同时根据谁在查看内容,显示用户是否购买了内容。因为物品和购买的数量可能会变得很大,所以我不愿意投入更多JOINs来实现这一点,因为那样看起来效果不佳。

基本上,我想did_i_buy在以下查询中的某处有一个字段,而不添加另一个JOIN. 这可能吗?让我们说user_name=tom

SELECT Items.item_id, item_name, COUNT(purchase_status='bought') as number_bought 
FROM Purchases
JOIN Items ON Purchases.item_id=Items.item_id
GROUP BY Items.item_id

这是我的数据库结构:

Table Items
item_id item_name
1           item_1
2           item_2
3           item_3

Table Purchases
item_id  purchase_status    user_name
1           bought          joe
2           bought          joe
1           bought          tom
1           bought          bill

期望的结果tom

item_id item_name number_bought did_i_buy
1        item_1         3        yes
2        item_2         1        no
4

2 回答 2

3

如果我理解正确,该did_i_buy栏的意思是“汤姆买了吗”。你可以这样做:

SELECT
  Items.item_id,
  item_name,
  COUNT(CASE WHEN purchase_status='bought' THEN 1 END) as number_bought,
  MAX(CASE WHEN purchase_status='bought' AND user_name='Tom' THEN 'yes' ELSE 'no' END) AS did_i_buy
FROM Purchases
JOIN Items ON Purchases.item_id=Items.item_id
GROUP BY Items.item_id

或者(一个CASE声明,见下面的评论)

SELECT
  Items.item_id,
  item_name,
  COUNT(purchase_status='bought') as number_bought,
  MAX(CASE WHEN user_name='Tom' THEN 'yes' ELSE 'no' END) AS did_i_buy
FROM Purchases
JOIN Items ON Purchases.item_id=Items.item_id
WHERE purchase_status='bought'
GROUP BY Items.item_id

还有一个调整:由于该WHERE子句,COUNT只会看到行 where purchase_status='bought',所以检查状态的表达式可以省略(上面唯一的变化是在第 4 行):

SELECT
  Items.item_id,
  item_name,
  COUNT(*) as number_bought,
  MAX(CASE WHEN user_name='Tom' THEN 'yes' ELSE 'no' END) AS did_i_buy
FROM Purchases
JOIN Items ON Purchases.item_id=Items.item_id
WHERE purchase_status='bought'
GROUP BY Items.item_id
于 2013-06-10T17:04:29.203 回答
0

You must (I think) use subqueries. Each request for a count is a separate query, so there is no way to optimize this (except to compress it all into one query with subqueries). There is no special relation between the horizontal data in items with the vertical data in purchases.

Here is an example query to count transactions for users:

SELECT user_id,(SELECT count(*) FROM transactions WHERE buyer_id=u.user_id) as count FROM users as u

I did a comparison with this query versus a similar query of the other JOIN type. The result: 0.0005 for this one vs. 0.0018 Ed Gibbs. However, if sorting of the number_bought (ORDER BY count DESC) is required, the latter query is significantly faster.

于 2013-06-10T17:09:06.180 回答