【问题标题】:Table 1 record should not be present in Table 2表 1 记录不应出现在表 2 中
【发布时间】:2020-10-12 13:29:30
【问题描述】:

我在mysql的同一个数据库中有两个表:

  1. 表 1
  2. 表 2

我正在使用 phpmyadmin 和 php。

我在两个表中都有“teamid”列,表 1 包含几个不同的事件列。 所以我从table1中取出了参加特定活动的teamid。

我在 table2 中也有列 teamid,他们参加了特定的活动。所以我也从table2中抽出了参加特定活动的teamid。

查询 1:Select teamid From table1 where event1pay='Paid'
查询 2:Select teamid From table2 where event='event1'

所以从查询 1 和查询 2 中,我取出了 teamid。

表 1:有 55 条记录

Table2:它有 5 条记录。

我希望 table1 teamid 记录不应该出现在 table2 teamid 记录中。

所需的查询应返回 50 条记录。

我已经应用了 Left Join,NOT IN 但它不起作用,因为上述两个查询都有不同的 where 子句。

【问题讨论】:

  • 那么,您遇到了什么问题?这里没有足够的代码来帮助你,或者它是如何让你失望的。
  • 你试过on table1.teamid != table2.teamid 吗?
  • 请显示您尝试的查询并解释它是如何失败的。
  • 两个表中都有列 teamid。我希望 table1 teamid 记录不应该出现在 table2 列 teamid 中。表 1 中有许多事件我从表 1 中提取了参与并为相应事件付费的 teamid。 Table2 有只参加过相应赛事的队伍。所以我只想 table1 teamid 列记录不应该出现在 table2 teamid 列中
  • 为什么不修改问题,让t1有10条记录,t2有2条记录,见meta.stackoverflow.com/questions/333952/…

标签: php mysql sql subquery left-join


【解决方案1】:

我会推荐not exists

select *
from table1 t1
where  event1pay = 'Paid' and not exists (
    select 1 
    from table2 t2 
    where t2.event = 'event1' and t2.teamid = t1.teamid
)

如果你想用反left join 来做这件事,那就是:

select t1.*
from table1 t1
left join table2 t2 on t2.teamid = t1.teamid and t2.event = 'event1'
where t1.event1pay = 'Paid' and t2.teamid is null

但我发现not exists 是表达你想在这里做的更好的方式。

【讨论】:

  • 非常感谢!!这是我正在寻找的查询。我已经检查了数据库,并且得到了所需的输出。再一次感谢你。我已经检查了不存在的查询并且它运行良好。
  • @RahulSahu 如果解决方案对您有用,那么您应该接受它作为答案而不是发表评论。
猜你喜欢
  • 2017-04-07
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 2015-11-08
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多