如何在mysql中交叉多个表

时间:2016-04-08 01:56:45

标签: php mysql intersect

我已经设置了一个php页面,因此有多个数据输入选项可以放入多个临时表中,每个临时表分别根据数据输入中给出的1个条件查询数据库。因此,如果输入是年龄> 10,鞋子化> 6和高度>在图60中,将存在三个临时表table0,table1和table2,其中table0仅是数据年龄> 10,table1仅是数据鞋化>图6和表2仅是数据高度> 60.

我想知道如何交叉这些,所以我只会得到满足所有要求的结果年龄> 10,鞋子化> 6和高度> 60.我尝试使用“WHERE EXISTS”条款如下,但它不起作用。

SELECT *
FROM table0 t0
WHERE EXISTS
    (SELECT *
     FROM table1 t1
     WHERE EXISTS
         (SELECT *
          FROM table2 t2
          WHERE t0.age = t1.age = t2.age
            AND t0.shoesize = t1.shoesize = t2.shoesize
            AND t0.height = t1.height = t2.height));

1 个答案:

答案 0 :(得分:0)

请注意,不依赖于表的主键这样的查询会变得很麻烦,所以我建议你添加一个主键。

也就是说,您需要的查询与您已经尝试过的查询非常接近:

SELECT *
FROM table0 t0
WHERE EXISTS (
          SELECT 1
          FROM table1 t1
          WHERE t1.age = t0.age AND t1.gender = t0.gender
            AND t1.shoesize = t0.shoesize AND t1.weight = t0.weight
            AND t1.height = t0.height AND t1.eyes = t0.eyes) AND
      EXISTS (
          SELECT 1
          FROM table2 t2
          WHERE t2.age = t0.age AND t2.gender = t0.gender
            AND t2.shoesize = t0.shoesize AND t2.weight = t0.weight
            AND t2.height = t0.height AND t2.eyes = t0.eyes)

注意 :只有当这些值都不为NULL时,上述查询才有效。