我有3张桌子:
我需要一个查询,该查询返回包含以下列的行:
这是我当前的查询,效果很好:
var x = [].slice.call(document.getElementsByClassName('moo'))
问题在于,奇怪的是,在SELECT store_cat.id_cat AS id,
CONCAT(store_cat.name, IFNULL(CONCAT(": ", GROUP_CONCAT(store_cat_attribute.name ORDER BY store_cat_attribute.position SEPARATOR ", "), ""), "")) AS name,
COUNT(DISTINCT store_item.id_item) AS products
FROM store_cat
LEFT JOIN store_item ON store_item.id_cat = store_cat.id_cat
LEFT JOIN store_cat_attribute ON store_cat_attribute.id_cat = store_cat.id_cat
WHERE store_cat.id_store = 1
GROUP BY store_cat.id_cat
ORDER BY name
列的其中一行中,复制了name
中的属性:
类别:属性1,属性1,属性2,属性2,属性3,属性3
关于为什么发生这种情况以及如何解决的任何想法?谢谢!
在这里您可以检查sqlfiddle:http://sqlfiddle.com/#!9/7da2d3/5
答案 0 :(得分:1)
您正在计算同一查询中的两个不同的事物(GROUP_CONCAT
和COUNT
)。 JOIN
至store_item
将导致重复。您可以将其移到选择列中:
SELECT
store_cat.id_cat AS id,
CONCAT(store_cat.name, IFNULL(CONCAT(": ",
GROUP_CONCAT(
store_cat_attribute.name
ORDER BY store_cat_attribute.position
SEPARATOR ", "
), ""
), ""
)) AS name,
(select count(distinct store_item.id_item) from store_item where store_item.id_cat = store_cat.id_cat) AS products
FROM store_cat
LEFT JOIN store_cat_attribute ON store_cat_attribute.id_cat = store_cat.id_cat
WHERE store_cat.id_store = 1
GROUP BY store_cat.id_cat, store_cat.name
ORDER BY name