我有三张桌子:
当我搜索ac
时,我需要搜索每个表并获取以ac
开头的所有行。
我还需要提取
我的搜索是使用自动填充,但我不想在一个大块中显示结果,而是将结果划分为商店,品牌和购物中心。
我目前的解决方案是执行3个单独的SQL查询,并将结果放在ann数组中并返回。
但我不觉得以这种方式进行查询是最有效的方法。有没有更好的方法来提高我的搜索速度?复杂搜索是否有最佳实践?
我正在索引姓名和地址等内容。
目前我只能使用MySQL DB。
答案 0 :(得分:1)
在不知道您的确切表格结构的情况下,我会提出与此相似的内容:
SELECT
stores.name AS name,
addresses.street AS street,
addresses.city AS city,
'store' AS type,
GROUP_CONCAT(categories.categoryname) AS category
FROM
stores
INNER JOIN
addresses ON addresses.addressid = stores.storeid
INNER JOIN
categories AS categories.storeid = stores.storeid
WHERE
stores.name LIKE "ac%"
GROUP BY
stores.storeid
UNION
SELECT
brands.name AS name,
'-' AS street,
'-' AS city,
'brand' AS type,
GROUP_CONCAT(brandcategories.categoryname) AS category
FROM
brands
INNER JOIN
brandcategories AS brandcategories.brandid = brands.brandid
WHERE
brands.name LIKE "ac%"
GROUP BY
brands.brandsid
UNION
SELECT
malls.name AS name,
addresses.street AS street,
addresses.city AS city,
'mall' AS type,
'-' AS category
FROM
malls
INNER JOIN
addresses ON addresses.addressid = malls.mallid
WHERE
malls.name LIKE "ac%"
GROUP BY
malls.mallid
为每个表和UNION执行SELECT...
。每个SELECT都有一个列type
,其中type可以是store,brand或mall。因此,您可以稍后在PHP代码中区分它。
因为UNION中的每个SELECT都需要相同的列,所以SELECT也需要相同的列。品牌返回一个地址,但它是空的。
在此示例中,每个商店/品牌都可以有多个类别,这些类别会以逗号分隔的字段(GROUP_CONCAT(categories.categoryname)
)立即返回。