1

选择查询

SELECT a. * , d.agent_id, COUNT( d.driver_id ) AS `noofdrivers`
                                      FROM ta_agent a, ta_drivers d
                                      WHERE a.agent_id = d.agent_id
                                      AND a.agent_id = ".$agent_id."
                                      GROUP BY a.agent_id

SELECT 查询返回以下记录

agent_id  agent_name company_name  pricing_plan  noofdrivers
--------  ----------  -----------  ------------  -----------
    3         CCC           ZZZ          8499       2
    2         BBB           YYY          3499       3    

驱动程序数据库表

agent_id  driver_id   driver_name
--------  ----------  -----------
2         1           EEE
2         2           FFF
2         3           GGG
1         4           HHH
3         5           III
3         6           JJJ

如何根据上述 SELECT 查询结果插入记录。如果pricing_plan是 3499 agent_id2 只能添加 5 个驱动程序。现在,agent_id2 有 3 个驱动程序。所以,他仍然只能添加 2 个驱动程序。如何在mysql查询中做这个限制限制?

4

2 回答 2

1

尝试这个,

insert into driver(driver_id, agent_id, driver_name)
   select ins.driver_id, ins.agent_id, ins.driver_name
   from (select 7 as driver_id, 2 as agent_id, 'KKK' as driver_name) ins
   where (select count(*) 
      from driver d, agent a
      where d.agent_id=a.agent_id and a.agent_id=ins.agent_id and a.pricing_plan=3499)<5;

在给定的查询中,您必须分别放置 variables$driver_id和for values$agent_id和。$driver_name72'KKK'

所以,它看起来像,

$sql="insert into driver(driver_id, agent_id, driver_name)
   select ins.driver_id, ins.agent_id, ins.driver_name
   from (select $driver_id as driver_id, $agent_id as agent_id, $driver_name as driver_name) ins
   where (select count(*) 
      from driver d, agent a
      where d.agent_id=a.agent_id and a.agent_id=ins.agent_id and a.pricing_plan=3499)<5";

这是演示 SQLFiddle

于 2014-04-23T09:00:56.573 回答
0

你可以使用这样的东西:

insert into ta_drivers(agent_id, driver_id, driver_name) SELECT (agent_id, driver_id, driver_name) FROM dual where ((SELECT a. * , d.agent_id, COUNT( d.driver_id ) AS `noofdrivers`
                                  FROM ta_agent a, ta_drivers d
                                  WHERE a.agent_id = d.agent_id
                                  AND pricing_plan=3499 and a.agent_id = ".$agent_id."
                                  GROUP BY a.agent_id)<5);

您必须检查查询,因为不正确。但理论上:

insert into table select from dual where ((select count(*) condition) <5);
于 2014-04-23T08:46:46.150 回答