Mysql乘以相同记录的数量

时间:2016-05-23 06:46:31

标签: mysql sql database records

这是一个简单的查询

$fetch_comb = mysql_query("SELECT code_id , atb_name_id FROM products_attributes pa WHERE pa.products_id = $products_id ");

我有这样的输出

-----------------------
| code_id |atb_name_id|
-----------------------
| 1       |    31     |
| 2       |    31     |
| 3       |    31     |
| 4       |    31     |
| 5       |    34     |
| 6       |    34     |
| 7       |    37     |
| 8       |    37     |
| 9       |    37     |

column `atb_name_id` has
"31" = 4 records, 
"34" = 2 records and
"37" = 3 records

我想在查询中将这些记录相乘,即4 * 2 * 3 = 24

1 个答案:

答案 0 :(得分:9)

SQL中没有PRODUCT函数,但有一个workaround。你可以试试这个:

SELECT CEILING(EXP(SUM(LOG(cnt))))
FROM (
    SELECT atb_name_id, COUNT(*) AS cnt
    FROM products_attributes pa 
    WHERE pa.products_id = $products_id
    GROUP BY atb_name_id
) t

ONLINE DEMO