'和' mysql中的(id数组)的条件

时间:2017-03-31 12:24:25

标签: mysql sql

我有一个像这样的mysql表。

+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+
| id | sku      | sellerID | name                                                                      | mode | created             |
+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+
|  1 | Sample   |        1 | SampleItem                                                                |    1 | 2016-05-20 12:04:33 |
|  2 | Sample   |        2 | Sample1                                                                   |    1 | 2016-06-14 12:23:24 |
|  3 | SDGS046  |        1 | Shivaprasad                                                               |    2 | 2016-06-18 05:26:27 |
|  4 | PAWA006  |        1 | Panda Baby Walker Music                                                   |    2 | 2016-06-18 06:19:10 |
|  5 | PAWA005  |        1 | WonderKart Panda Walker for Kids (colour may vary)                        |    2 | 2016-06-18 06:24:23 |
|  6 | WKBR1301 |        1 | Planet of Toys New Born Toddler Protable Rocker                           |    2 | 2016-06-18 06:26:30 |
|  7 | PAKS001  |        1 | Panda Baby Musical Swing With Multiple Age Settings | 4 Stages | (Orange) |    2 | 2016-06-18 06:28:19 |
|  8 | WKGS046  |        1 | The Flyers Bay Flyer's Bay Ultra Durable Big Wheel Scooter (Silver)       |    2 | 2016-06-18 06:57:25 |
|  9 | MABS001  |        1 | Mastela Booster to Toddler 6M+ Seat (DarkGray)                            |    2 | 2016-06-20 06:25:00 |
| 10 | WKGS546  |        1 | Saffire Kids Scooter with Tractor Wheels Green                            |    2 | 2016-06-20 06:26:50 |
+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+

我希望通过查询获取数据,如。

SELECT * FROM `sku` WHERE `sellerID` = 1 AND id = 3 AND id = 4 AND id = 10;

但是我试着这样做

SELECT * FROM sku WHERE sellerID = 1 AND id IN (3,4,10);

它返回行,如果id(3,4,10)表中有任何可用的,但我想要返回行,如果表中有每个id(3和4和10)。

我想传递一个数组来检查AND条件。如果有任何解决方案,请建议我。

3 个答案:

答案 0 :(得分:1)

您可以使用聚合来计算每个卖家的匹配行:

SELECT sellerId
FROM `sku`
WHERE id IN (3, 4, 10)
GROUP BY sellerId
HAVING COUNT(DISTINCT id) = 3;

如果您想要原始行,可以使用此查询为匹配的sellerId引入适当的行。

答案 1 :(得分:0)

我会计算子查询中与原始where条件匹配的记录数,如果该计数为3,则仅进行选择:

SELECT * FROM sku
WHERE sellerID = 1
    AND id IN (3,4,10) 
    AND 3 = (SELECT count(*) FROM sku WHERE sellerID = 1 AND id IN (3,4,10));

答案 2 :(得分:0)

您可以使用所有功能来完成您的要求。但为此你应该使用子查询来处理这个条件。

SELECT * FROM sku WHERE sellerID = 1 AND id=all (select sellerID  from sku where sellerID in (3,4,10));

或者如果您直接从某个查询中获取这些值,那么您可以将其作为子查询包含在内。

SELECT * FROM sku WHERE sellerID = 1 AND id=all (select sellerID  from from_ur_table_for_codition);