Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql查询不存在,无法正常工作_Mysql_Sql_Database_Not Exists - Fatal编程技术网

Mysql查询不存在,无法正常工作

Mysql查询不存在,无法正常工作,mysql,sql,database,not-exists,Mysql,Sql,Database,Not Exists,我有以下两个表和列 表1:transactionid 表2:transactionid和状态 如果表2中不存在相同的transactionid,我需要从表1中获取结果 如果table2中存在相同的transactionid,但状态不同于2,则不应返回table1行 如果表2中存在相同的transactionid,并且状态为2,那么它应该返回表1行,但我需要知道这一点,以便在我的网站中显示错误 我目前有: select * from table1 where not exists (select

我有以下两个表和列

表1:transactionid

表2:transactionid和状态

如果表2中不存在相同的transactionid,我需要从表1中获取结果

如果table2中存在相同的transactionid,但状态不同于2,则不应返回table1行

如果表2中存在相同的transactionid,并且状态为2,那么它应该返回表1行,但我需要知道这一点,以便在我的网站中显示错误

我目前有:

select * from table1 where not exists (select null from table2
            WHERE table1.transactionid = table2.transactionid AND status <> 2)
我需要这样的东西它不能正常工作

select *, (select count(*) from table2 where table1.transactionid = table2.transactionid AND status = 2) as orderswitherrors from table1 where not exists (select null from table2
            WHERE table1.transactionid = table2.transactionid AND status <> 2)
因此,在php中,我可以检查transactionid在表2中是否有错误,即if$row->orderswitherrors>0


谢谢你

我认为你试图使用EXISTS太麻烦了

在这个查询中,我们只是使用联接将表1和表2都放入结果集中。我们使用左联接,这样即使表2中不存在表1中的行,也会返回这些行。如果没有匹配的行,结果集将包含所有Table2列的NULL

一旦我们有了一个包含两个表的结果集,我们只需过滤这些行,这样我们只保留表2中没有行的行,或者有行且状态为2的行

SELECT    table1.*, 
          table2.status
FROM      table1
LEFT JOIN table2 ON table1.transactionid = table2.transactionid
WHERE     table2.transactionid IS NULL   --Doesn't exist in table2
OR        table2.status = 2              --Exists in table2 with status 2

您可以在case语句中使用“left join”来获取状态为的事务id,并根据状态显示/隐藏错误,例如:

SELECT t1.transactionid, 
CASE WHEN t2.status IS NULL THEN 'NOT_EXISTS'
WHEN t2.status = 2 THEN 'ERROR'
END AS state
FROM table1 t1 LEFT JOIN table2 t2 ON t1.transactionid = t2.transactionid
WHERE t2.status IS NULL OR t2.status = 2
ORDER BY t1.transactionid;
以下是。

您可以使用“不存在”和“存在”组合:

select t1.*
from table1 t1
where not exists (select 1
                  from table2 t2
                  where t1.transactionid = t2.transactionid
                 ) or
      exists (select 1
              from table2 t2
              where t1.transactionid = t2.transactionid and
                    status = 2
             );

我想请你在你的答案周围多加一些上下文。只有代码的答案很难理解。如果你能在你的文章中添加更多的信息,这将有助于询问者和未来的读者。感谢您的帮助,但是如果表2中的某一行中存在状态1,则我不需要返回任何结果。谢谢