gpt4 book ai didi

mysql - 如何查询mysql以按多个值进行选择和分组

转载 作者:太空宇宙 更新时间:2023-11-03 12:08:17 26 4
gpt4 key购买 nike

我正在尝试根据下表的所有 contentid 值进行选择和分组,其中匹配条件可以是多个不同的值。

contentid 值实际上代表汽车,所以我需要选择 [并分组依据] 所有 contentis,其中值为“GMC”,值为“sedan”,值为“automatic”。

即我正在尝试选择所有配备自动变速箱的 GMC 轿车。

这样的查询[显然]失败了:

select * from modx_site_tmplvar_contentvalues WHERE
`value` = 'gmc' and
`value` = 'tacoma'
group by contentid

我不知道如何创建这样的查询。有什么建议么?

table structure

最佳答案

您需要在“tmplvarid”上“透视”这些数据,但不幸的是,MySQL 没有像其他 RDBMS 那样的 PIVOT 语句。但是,您可以通过多次加入表中您关心的每个变量来自行调整它:

SELECT
contents.contentid,
transmission.value as transmission,
type.value as type,
make.value as make
FROM
(SELECT DISTINCT contentid FROM modx_site_tmplvar_contentvalues) AS contents
LEFT JOIN
modx_site_tmplvar_contentvalues AS transmission
ON contents.contentid = transmission.contentid
AND transmission.tmplvarid = 33 -- id for transmission
LEFT JOIN
modx_site_tmplvar_contentvalues AS make
ON contents.contentid = make.contentid
AND make.tmplvarid = 13 -- id for make
LEFT JOIN
modx_site_tmplvar_contentvalues AS type
ON contents.contentid = type.contentid
AND type.tmplvarid = 17 -- id for type
WHERE
type.value = 'sedan'
AND make.value = 'GMC'
AND transmission.value = 'automatic'

您可以使用其他标准(例如年份(id 15)或里程(id 16))的附加连接来扩展它。

如果你只需要使用值,你可以尝试:

SELECT DISTINCT
contents.contentid,
transmission.value as transmission,
type.value as type,
make.value as make
FROM
(SELECT DISTINCT contentid FROM modx_site_tmplvar_contentvalues) AS contents
INNER JOIN
modx_site_tmplvar_contentvalues AS transmission
ON contents.contentid = transmission.contentid
AND transmission.value = 'automatic'
INNER JOIN
modx_site_tmplvar_contentvalues AS make
ON contents.contentid = make.contentid
AND make.value = 'GMC'
INNER JOIN
modx_site_tmplvar_contentvalues AS type
ON contents.contentid = type.contentid
AND type.value = 'sedan'

无论如何,请确保您在值列上有一个索引;这些查询会变慢。

关于mysql - 如何查询mysql以按多个值进行选择和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25416701/

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