Mysql数据库上的Django Intersection

时间:2019-02-16 14:19:19

标签: mysql sql django

我的表具有以下值:

id, product, category
1,     A,       1
2,     B,       1
3,     B,       2
4,     C,       1
5,     C,       2
6,     D,       2
7,     E,       2
8,     E,       3
9,     F,       3
10,    F,       4

我只需要选择与Django中类别(1 OR 2)和类别(3 OR 4)匹配的产品。预期结果仅是产品:E

我遇到错误“ mysql不支持交叉点”如何使用Q()实现此目的?

此查询不返回任何结果,但有效。

main_query = Q()
main_query &= Q(category__in=[1,2])
main_query &= Q(category__in=[3,4])
models.Table.objects.filter(main_query)

4 个答案:

答案 0 :(得分:4)

SELECT product
FROM yourTable
GROUP BY product
HAVING COUNT(CASE WHEN category IN (1,2) THEN 1 END) > 0
   AND COUNT(CASE WHEN category IN (3,4) THEN 1 END) > 0

答案 1 :(得分:2)

这是内联表的一种选择。

SELECT a.* FROM 
 (SELECT * FROM tab  WHERE category IN (1,2)) AS a,
 (SELECT * FROM tab  WHERE category IN (3,4)) AS b
WHERE a.product = b.product ;

演示here

另一个使用WITH子句的选项,如下所示:

WITH cat_1_2 AS (
  SELECT * FROM tab  WHERE category IN (1,2)
),
cat_3_4 AS (
  SELECT * FROM tab  WHERE category IN (3,4)
)
SELECT a.* FROM cat_1_2 AS a, cat_3_4 AS b
WHERE a.product = b.product ;

演示here

答案 2 :(得分:1)

AND条件将应用到每一行,因此您没有预期的结果..而是选择与IN子句中的类别关联的行。

您可以尝试在子查询上使用几个内部联接

    SELECT t.* 
    FROM table t
    INNER JOIN (SELECT 1  cat
                UNION
                SELECT 2) t1 ON  t1.cat = t.category 
    INNER JOIN (SELECT 3 cat
                UNION
                SELECT 4) t2 ON t2.cat = t.category 

答案 3 :(得分:0)

我从@RajmondNijland得知INTERSECT在MySQL中不存在。谢谢他因此,您可以将以下查询与IN运算符配合使用,以将子查询与主链接:

SELECT product 
  FROM table1 
 WHERE category IN (1,2) 
   AND product IN ( SELECT product FROM table1 WHERE category IN (3,4) );

product
-------
E