如何从多个查询中进行乘法和除法?

时间:2013-12-09 02:17:12

标签: mysql sql

所以现在我有3个查询:

让我们调用此查询X

SELECT count(*) as totalDrink from 
Drink D join History H where H.drinkName = D.name AND type = 'vodka' and userID = 'sai' 

查询Y

SELECT count(*) as totalDrink from 
Drink D join Favorite F where F.drinkName = D.name AND type = 'vodka' and userID = 'sai' 

查询Z

SELECT SUM(totalDrinks) as total FROM (
SELECT COUNT(*) totalDrinks FROM History
WHERE userID = 'sai'
UNION ALL
SELECT COUNT(*) FROM Favorite
WHERE userID = 'sai'
) as totalDrink

基本上我想在mySQL中输出:

(X + Y(0.666))/ Z

1 个答案:

答案 0 :(得分:0)

最直接:

SELECT (
  (
    SELECT COUNT(*)
    FROM   Drink D JOIN History  H ON H.drinkName = D.name
    WHERE  type = 'vodka' AND userID = 'sai'
  ) + (
    SELECT COUNT(*)
    FROM   Drink D JOIN Favorite F ON F.drinkName = D.name
    WHERE  type = 'vodka' AND userID = 'sai' 
  )
) / (
  (
    SELECT COUNT(*) FROM History  WHERE userID = 'sai'
  ) + (
    SELECT COUNT(*) FROM Favorite WHERE userID = 'sai'
  )
)