如何查询mysql以选择多个值并进行分组

时间:2014-08-21 00:50:56

标签: mysql

我尝试按下表中所有有争议的值进行选择和分组,其中匹配条件可以是几个不同的值。

contentid值实际上代表汽车,所以我需要选择[和分组]所有内容,其中值是' GMC'并且价值观是“轿车”。并且值是自动的。

即。我尝试用自动变速箱选择所有GMC轿车。

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

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

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

table structure

4 个答案:

答案 0 :(得分:2)

你需要"转动"关于" 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'

在任何情况下,请确保您在值列上有索引;这些查询会变慢。

答案 1 :(得分:1)

请试试这个:

SELECT *
FROM modx_site_tmplvar_contentvalues t1 INNER JOIN modx_site_tmplvar_contentvalues t2 ON t1.contentid = t2.content_id
WHERE
  t1.`value` = 'gmc'
  AND t2.`value` = 'tacoma';

答案 2 :(得分:0)

这总是错误的:

  

`value` ='gmc'和
  `value` ='tacoma'

相反,请使用OR:

  

`value` ='gmc'或
  `value` ='tacoma'

在某种情况下,“和”意味着“这同时也是如此”。如果你想要所有的foos和所有酒吧,那么你的条件是“foo OR bar”。

修改
要选择包含值的组,您可以编写子查询:

SELECT DISTINCT name FROM table WHERE name IN (SELECT name FROM table WHERE value='value1') AND name IN (SELECT name FROM table WHERE value='value2')

答案 3 :(得分:0)

您可以使用group by执行此操作。在表达条件方面,这是最灵活的。在MySQL中,多个连接通常会表现得更好:

select contentid
from modx_site_tmplvar_contentvalues 
group by contentid
having sum(`value` = 'gmc') > 0 and
       sum(`value` = 'tacoma') > 0;