mysql - 如何将 MySQL WHERE IN 语句与子查询一起使用?

标签 mysql

表格

mysql> SELECT * FROM swaps_products;

+----+---------+-----------+------------+-----------+---------------------+
| id | swap_id | holder_id | swap_to_id | product_id| added               |
+----+---------+-----------+------------+-----------+---------------------+
|  1 |       9 |         3 |          0 |        32 | 2017-01-06 10:43:52 |
|  2 |      11 |        13 |          0 |         3 | 2017-01-06 11:03:45 |
|  3 |      11 |        13 |          0 |         4 | 2017-01-06 11:03:45 |
|  4 |      11 |         3 |          0 |        32 | 2017-01-06 11:03:45 |
|  5 |      11 |         3 |          0 |        31 | 2017-01-06 11:03:45 |
|  6 |      11 |         3 |          0 |        30 | 2017-01-06 11:03:45 |
|  7 |      12 |         3 |          0 |        32 | 2017-01-06 14:16:13 |
|  8 |      12 |         3 |          0 |        31 | 2017-01-06 14:16:13 |
|  9 |      12 |         2 |          0 |         2 | 2017-01-06 14:16:13 |
| 10 |      12 |         2 |          0 |         1 | 2017-01-06 14:16:13 |
| 11 |      13 |        13 |          3 |         3 | 2017-01-12 14:31:44 |
| 12 |      13 |        13 |          3 |         4 | 2017-01-12 14:31:44 |
| 13 |      13 |         3 |         13 |        32 | 2017-01-12 14:31:44 |
| 14 |      13 |         3 |         13 |        31 | 2017-01-12 14:31:44 |

对于swap_id = 13,涉及四种产品 - 3、4、31、32。我需要查询,该查询将为我提供所有其他涉及 3,4,31,32 个产品中的任何交换(swap_id 列表)。

我有这个

SELECT sp.swap_id as swap_id, sp.holder_id as holder_id
    -> FROM swaps_products as sp
    -> JOIN swaps as s
    -> ON s.id=sp.swap_id
    -> WHERE (sp.swap_id != 13) AND
    -> (s.rejected IS NULL) AND
    -> ((s.swapped IS NULL) OR (s.swapped2 IS NULL)) AND
    -> (sp.product_id IN (3,4,31,32));

JOIN 对于问题来说并不重要。这个查询有效,但问题是我只知道 swap_id。所以我尝试了这个:

(sp.product_id IN (SELECT product_id FROM swaps_products WHERE swap_id = 13));

但出现错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'JOIN swaps as s
ON s.id=sp.swap_id
WHERE (sp.swap_id != 13) AND
(s.rejected IS N' at line 2

我认为问题是子查询没有返回 IN 语句所期望的数组。

最佳答案

IN 语句要求结果是要检查的单列值向量。

直接回答您的询问:

从 swaps_products 中选择*,其中product_id位于 (从 swaps_products 中选择 Product_id,其中 swap_id = 13) 并且 swap_id != 13

此外,根据上面的错误消息,您遇到的语法错误指向第2行;我怀疑您在 where...in 查询中遗漏了 FROM swaps_products as sp 部分。

关于mysql - 如何将 MySQL WHERE IN 语句与子查询一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41617633/

相关文章:

mysql - 如何统计同一个表不同列中的外键?

php - 我怎样才能为多表结果做 Laravel 分页?

php - 图像上传上的未识别索引(PHP,Mysql)

php - UTF-8贯穿始终

c# - Entity Framework 6.1 Code First MySql 实体跟踪在上下文中持续存在

php mysql查询字符串数组

来自查询文件的 Mysqldump

PHP mysql_connect 设置等待超时

php - mysql : updating existing column using the column value in prepared query

mysql - delphi插入SQL语法错误