【问题标题】:Mysql count, join, and dual in conjunctionMysql的count、join和dual的结合
【发布时间】:2014-03-21 20:47:00
【问题描述】:

我有一个表测试器,它有一个主 id 和一个引用名为 test 的表的 id 的外键。

测试表有一个 numAllowed 列,指示有多少人可以参加此特定测试。

我想插入一个新的测试人员,其测试列仅在引用同一测试的测试人员少于该特定测试的 numAllowed 时才引用该测试。例如,测试员“Alex”只有在少于 20 人 (numAllowed) 参加/已经参加的情况下才能参加“Geography”考试。

另外,count 函数如何在这样的查询中运行?它只计算连接中包含的列还是它的“范围”在查询之外?它会返回该表中所有 id 的计数吗?

   insert into tester (test, createddate, ipaddress) 
   select 
      11, NOW(), xxx.xxx.xxx.xxx 
   from 
      dual 
   where exists 
   ( select * from 
      test ts inner join 
         tester tr 
      on tr.test = ts.id 
      where ts.numAllowed - count(tr.id) > 0 
      and ts.id = '11')

【问题讨论】:

  • 您的dual 表中有什么?
  • 没什么,据我所知是选择自己的价值观。
  • 不知道 mySQL 是否支持 dual,但我很确定您不能在 WHERE 子句中使用 count() 之类的聚合函数。您需要对数据进行分组并使用 HAVING 子句。
  • 为什么不使用触发器来执行业务规则?

标签: mysql join count


【解决方案1】:

我会这样写你的查询:

INSERT INTO tester (test, createddate, ipaddress) 
SELECT
  test.ID, NOW(), 'xxx.xxx.xxx.xxx'
FROM
  test
WHERE
  test.ID = 1
  AND EXISTS (SELECT COUNT(*)
              FROM tester
              WHERE tester.test = test.ID
              HAVING test.numAllowed-COUNT(*)>0);

请看小提琴here

【讨论】:

    猜你喜欢
    • 2021-03-15
    • 2019-07-21
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多