MySQL 如何在同一列中选择多个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12594343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I select multiple values in the same column?
提问by Jude
I am trying to select multiple values in a single column. Basically I want the query to select all those under column family
with values Software_1Y
,XI_1Y
and P1_1Y
我试图在单列中选择多个值。基本上我希望查询选择列下的所有family
值Software_1Y
,XI_1Y
并且P1_1Y
I am running this query :
我正在运行这个查询:
SELECT `salesorder`
,`masterproduct`
,`family`
,`birthstamp`
,`duedate`
,COUNT(*) AS `total`
FROM `report`
WHERE `birthstamp` BETWEEN '$startDT'
AND '$endDT'
AND `family` = 'Software_1Y'
AND `family = 'XI_1Y'
AND `family` = 'PI_1Y'
GROUP BY `salesorder`
,`masterproduct`
,`family`
,`duedate`;
My query returns no rows but is I search each family one by one, I have values.
我的查询没有返回任何行,但是我是一个一个地搜索每个家庭,我有值。
What is wrong with my query?
我的查询有什么问题?
Also, my purpose is to get all the rows whose family
values are Software_1Y
, XI_1Y
and PI_1Y
.
另外,我的目的是获取family
值为Software_1Y
,XI_1Y
和 的所有行PI_1Y
。
回答by Adriaan Stander
How about using IN instead
改用 IN 怎么样
SELECT `salesorder`,
`masterproduct`,
`family`,
`birthstamp`,
`duedate`,
COUNT( * ) AS `total`
FROM `report`
WHERE `birthstamp` BETWEEN '$startDT' AND '$endDT'
AND `family` IN ('Software_1Y','XI_1Y','PI_1Y')
GROUP BY `salesorder`,
`masterproduct`,
`family`,
`duedate`;
The reason why no values are returned, is because of this section
没有返回值的原因,是因为这部分
AND `family` = 'Software_1Y'
AND `family = 'XI_1Y'
AND `family` = 'PI_1Y'
family
cannot be all 3 values at once, but it might be 1 of the 3 values.
family
不能同时是所有 3 个值,但它可能是 3 个值中的 1 个。
That is why you would use IN.
这就是为什么你会使用 IN。
Another way to look at it would be to use OR, but that gets really long winded.
另一种看待它的方法是使用 OR,但这会变得非常冗长。
回答by Viral Jain
$query=" SELECT `salesorder`,`masterproduct`,`family`,`birthstamp`,`duedate`, COUNT( * ) AS `total` FROM `report`
WHERE `birthstamp` BETWEEN '$startDT' AND '$endDT'
AND (`family` = 'Software_1Y'
OR `family` = 'XI_1Y'
OR `family` = 'PI_1Y')
GROUP BY `salesorder`,`masterproduct`,`family`,`duedate` ";
It must be due to AND instead of OR while querying FAMILY column.
在查询 FAMILY 列时,它必须是由于 AND 而不是 OR。
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
//Operation you want to perform
}
@jude: It seems you are directly passing the query which is of type string directly as a parameter to mysql_fetch_array, which is wrong. Instead follow the above approach...
@jude:看来您是直接将字符串类型的查询作为参数直接传递给mysql_fetch_array,这是错误的。而是按照上述方法...