MYSQL 问题:您可以将 IN 用于 2 个不同的字段吗?

MYSQL QUERY: Can you use IN with 2 different fields?

我的数据库有 2 个 table。一个 table 包含客户和产品,另一个 table 链接它们:

    Table 1: objects (id,name,id_type) where id_type is the type of object (1 client, 2 product)
    Table 2: object_relations (id,id_child,id_parent) where id_child and id_parent are objects.id.

我的初始查询向您显示已购买特定产品的特定客户。产品和客户如下例所示:

SELECT o.* 
FROM objects AS o 
    LEFT JOIN objects_relations AS o_r ON(o_r.id_child = o.id) 
WHERE o.type=1 
AND EXISTS (
        SELECT 
        FROM objects AS o9 
            LEFT JOIN objects_relations AS o_r9 ON (o_r9.id_child = o9.id) 
        WHERE o9.id=o.id 
        AND o_r9.id_parent=o_r.id_parent 
        AND (
                (o9.id=21 AND o_r9.id_parent=3) 
                OR (o9.id=21 AND o_r9.id_parent=5) 
                OR (o9.id=25 AND o_r9.id_parent=2) 
                OR (o9.id=25 AND o_r9.id_parent=7) 
                OR ...long list 
            )
        )

我很想看到另一种方法来实现特定产品和客户的长列表,例如 IN ()。有没有更好的方法?

您可以将嵌套列表与 IN

一起使用
AND (o9.id, o_r9.id_parent) in ((21, 3), (21, 5), (25, 2), (25, 7))

您可以使用 IN ( ) 谓词执行 tuple comparison

AND (o9.id, o_r9.id_parent) IN (
  (21, 3), (21, 5), (25, 2), (25, 7), ...
)

另一个选项是 MySQL 8.0 中支持的新语法:VALUES 语句允许您派生文字值表:

SELECT *
FROM objects AS o9
INNER JOIN objects_relations AS o_r9
INNER JOIN (
 VALUES ROW(21, 3), ROW(21, 5), ROW(25, 2), ROW(25, 7), ...
) AS t ON (o9.id, o_r9.id_parent) = (t.column_0, t.column_1) 

https://dev.mysql.com/doc/refman/8.0/en/values.html