gpt4 book ai didi

MYSQL使用group_concat获取搜索结果的数量

转载 作者:行者123 更新时间:2023-11-29 11:25:20 24 4
gpt4 key购买 nike

好吧,我花了几个小时和我的一个 friend 一起解决这个查询。我采用了一种新的“分层”结构,这意味着“子”(商店)填写数据并获取数据,或者不填写,因此父级(链,所述商店的创建者)具有默认信息然后应该捕获它。现在,我终于有了这个搜索功能来处理这个事实。它在技术上工作得很好(虽然我猜它不是很高效,但 SQL 确实不是我的强项)

现在,我遇到的问题是,在这个层次结构之前,我会将结果“总结”为它进行的匹配数。 但是,因为我现在正在做很多“非此即彼”的情况,所以这部分似乎变得很困惑。我已经尝试了很多东西(DISTINCT COUNTDISTINCT SUMCOUNTSUMTHEN 1 THEN +1THEN -1 等)

所以...是的...我真的很坚持这个。问题是,我需要计数器来对相关性进行排序。

SELECT stores.ID, store_info.display_name, store_info.address, store_info.phone, 
IFNULL(GROUP_CONCAT(DISTINCT smallCheese.display_name ORDER BY smallCheese.name),
GROUP_CONCAT(DISTINCT bigCheese.display_name ORDER BY bigCheese.name)
) AS brands,
IFNULL(GROUP_CONCAT( DISTINCT
CASE WHEN smallCheese.ID IN (3,5,8,11,12,13,14,16,17)
THEN smallCheese.display_name
ELSE NULL
END),
(GROUP_CONCAT(DISTINCT
CASE WHEN bigCheese.ID IN (3,5,8,11,12,13,14,16,17)
THEN bigCheese.display_name
ELSE NULL
END))
) AS available_brands,
COUNT(DISTINCT CASE WHEN smallCheese.ID OR bigCheese.ID IN (3,5,8,11,12,13,14,16,17)
THEN 1
ELSE 0
END ) AS available_brands_count
FROM stores
LEFT JOIN store_info ON (stores.ID = store_info.storeID)
LEFT JOIN store_brands ON (stores.ID = store_brands.store)
LEFT JOIN chain_brands ON stores.chainID = chain_brands.chain
LEFT JOIN brands AS smallCheese ON store_brands.brand = smallCheese.ID
LEFT JOIN brands AS bigCheese ON chain_brands.brand = bigCheese.ID
WHERE stores.city = 1
GROUP BY store_info.storeID
ORDER BY `available_brands_count` DESC, store_info.display_name

这是一个 SQL fiddle :http://sqlfiddle.com/#!9/cfe307/1/0

最佳答案

我认为这可能有效:

IF (MAX(CASE WHEN smallCheese.ID IN (3,5,8,11,12,13,14,16,17)
THEN smallCheese.ID
ELSE NULL
END) IS NOT NULL,
COUNT(DISTINCT
CASE WHEN smallCheese.ID IN (3,5,8,11,12,13,14,16,17)
THEN smallCheese.ID
ELSE NULL
END),
COUNT(DISTINCT
CASE WHEN bigCheese.ID IN (3,5,8,11,12,13,14,16,17)
THEN bigCheese.ID
ELSE NULL
END)) AS available_brands_count

您不能只使用 IFNULL(COUNT(...), COUNT(...)),因为 COUNT() 返回 0 code> 如果没有匹配项。我使用 MAX() 聚合所有 ID,如果没有找到 ID,则返回 NULL

DEMO

关于MYSQL使用group_concat获取搜索结果的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38317844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com