MySQL中有三个表连接计数

时间:2012-12-05 09:58:20

标签: mysql join count

我这里有问题;当我查询时:

SELECT product.*,product_description.*,COUNT(product_image.*) 
FROM " . DB_PREFIX . "product  
INNER JOIN product_description ON product.product_id = product_description.product_id 
INNER JOIN product_image ON product.product_id = product_image.product_id 
ORDER BY product.date_modified DESC

我想为table product_image选择3个表n 1个计数,但是我收到了这个错误:

  

注意:错误:您的SQL语法中有错误;检查手册   对应于您的MySQL服务器版本,以获得正确的语法   在')附近使用FROM产品INNER JOIN product_description ON   product.product_id = product_'在第1行错误号:1064 SELECT   产品。,product_description。,COUNT(product_image。)FROM产品   INNER JOIN product_description ON product.product_id =   product_description.product_id INNER JOIN product_image ON   product.product_id = product_image.product_id ORDER BY   product.date_modified DESC

3 个答案:

答案 0 :(得分:1)

您不应该使用COUNT这样的功能。加入表时COUNT(TableName.*)。您需要使用其中任何一列,例如COUNT(TableName.ColumnName)

例如COUNT(product_image.ID)

See this SQLFiddle

答案 1 :(得分:0)

使用派生查询计算

SELECT 
    product.*,
    product_description.*,
    pi.Count as T_Count
FROM " . DB_PREFIX . "product  
INNER JOIN product_description ON product.product_id = product_description.product_id 
INNER JOIN (SELECT product_id , count(*) as Count FROM product_image) as pi ON product.product_id = pi.product_id 
ORDER BY product.date_modified DESC

答案 2 :(得分:0)

试试这个::

SELECT 
product.*,
product_description.*,
COUNT(1) 
FROM " . DB_PREFIX . "product  
INNER JOIN product_description ON product.product_id = product_description.product_id 
INNER JOIN product_image ON product.product_id = product_image.product_id 
ORDER BY product.date_modified DESC