为什么EXCEPT功能不起作用?

时间:2017-12-29 21:20:33

标签: php mysql except

我有如下所示的mysql查询:

$missingTypo = mysql_query("SELECT m.ID
                              FROM table1 AS m
                              LEFT JOIN table2 AS ut
                              ON ut.matchID = m.ID
                              WHERE data > '$now'
                          EXCEPT
                            SELECT m.ID
                              FROM table1 AS m
                              LEFT JOIN table2 AS ut
                              ON ut.matchID = m.ID
                              WHERE data > '$now' 
                              AND ut.typer = '$name'");

第一个状态查询返回3个结果[10,11,12],第二个返回1个结果[10]。整个查询的结果应该是[11,12],但它不起作用。 var_dump函数返回false。 但是,如果我交换"除了"例如" UNION ALL"它工作正常并给出[10,11,12,10]。

请帮忙。

2 个答案:

答案 0 :(得分:1)

正如另一个答案所示,Mysql不支持EXCEPT,但您可以使用NOT IN谓词:

SELECT m.ID
FROM table1 AS m
LEFT JOIN table2 AS ut ON ut.matchID = m.ID
WHERE data > '$now'
  AND m.ID NOT IN(SELECT m2.ID
                  FROM table1 AS m2
                  INNER JOIN table2 AS ut ON ut.matchID = m.ID
                  WHERE data > '$now' 
                    AND ut.typer = '$name');

LEFT JOIN

SELECT t1.ID
FROM
(
  SELECT m.ID
  FROM table1 AS m
  LEFT JOIN table2 AS ut ON ut.matchID = m.ID
  WHERE data > '$now'
) AS t1
LEFT JOIN
(
  SELECT m.ID
  FROM table1 AS m
  LEFT JOIN table2 AS ut ON ut.matchID = m.ID
  WHERE data > '$now' 
    AND ut.typer = '$name'
) AS t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL

答案 1 :(得分:0)

MySQL不支持EXCEPT,而是使用WHERE NOT