如何结合myqsl查询?

时间:2018-01-23 12:23:36

标签: mysql

true

$ ID = 100100;

//找到最高价

I have 2 tables like this:

table:prices
id, project_id, real_min_price, real_max_price
1 | 100100 | 500  | 2000 
2 | 100100 | 900  | 3000 
3 | 100100 | 2500 | 3200
4 | 100100 | 320  | 3900

table:gifts
id, project_id, min_price, max_price, gift
1 | 100100 | 0    | 1000 | 10
2 | 100100 | 1001 | 2000 | 20
3 | 100100 | 2001 | 3000 | 30
4 | 100100 | 3001 | 4000 | 40
5 | 100100 | 4001 | 5000 | 50
6 | 100100 | 5001 | 6000 | 60

- 返回3900

//找到此值的最小 - 最大列

之间的限制行
SELECT MAX(real_max_price) FROM `prices` WHERE project_id='$ID';

$MAX_PROJECT_PRICE = $dbo->getOne();

- 创建第四行礼品表并返回40

//删除高于MAX_GIFT值

的其他礼品行
SELECT gift FROM `gifts` WHERE project_id='$ID' 
AND max_price>='$MAX_PROJECT_PRICE' ORDER BY max_price ASC LIMIT 1;

$MAX_GIFT = $dbo->getOne();

- 删除了第5行和第6行。

在这种情况下

它会发现最高价格为" 3900"所以,第5和第6排礼品表将被删除。

但这种方式非常糟糕,应该在一个查询中完成,但是如何?

2 个答案:

答案 0 :(得分:1)

  

好的,你可以删除查询,至少我们可以先组合   2个查询以查找MAX_GIFT值。

要结合您可以执行的前两个查询。

<强>查询

SELECT
    gift
FROM
    gifts
WHERE
    project_id = 100100 
    AND max_price >= (SELECT MAX(real_max_price)
                      FROM prices
                      WHERE project_id = 100100;)
ORDER BY
    max_price ASC
LIMIT 1;

将所有三个查询合并为一个。

<强>查询

DELETE FROM
  gifts
WHERE
     project_id = 100100
  AND
     gift > (SELECT
               gift
             FROM
               gifts
             WHERE
                project_id = 100100 
              AND
                max_price >= (SELECT
                                MAX(real_max_price)
                              FROM
                                prices
                              WHERE   
                                 project_id = 100100;
                             )
              ORDER BY
                max_price ASC
              LIMIT 1
           )

答案 1 :(得分:0)

以下是根据您的查询条件运行delete命令的解决方案:

delete from gifts where gift in
(
  select gift from 
  (
  select gift, @row:=@row+1 as rw 
    from gifts, (select @row:=0) a
   where (select max(real_max_price) 
            from prices 
           where project_id=100100 limit 1) < max_price
     and project_id = 100100
    order by gift
  ) sub
  where rw>1
);

样本数据和测试。

create table prices (
id integer,  
project_id integer, 
real_min_price integer, 
real_max_price integer
);

create table gifts (
id integer,  
project_id integer, 
min_price integer, 
max_price integer,
gift integer
);

insert into prices values
(1,100100,500,2000),
(2,100100,900,3000), 
(3,100100,2500,3200),
(4,100100,320,3900);

insert into gifts values
(1 , 100100 , 0    , 1000 , 10),
(2 , 100100 , 1001 , 2000 , 20),
(3 , 100100 , 2001 , 3000 , 30),
(4 , 100100 , 3001 , 4000 , 40),
(5 , 100100 , 4001 , 5000 , 50),
(6 , 100100 , 5001 , 6000 , 60);

运行我提供的查询,您将获得礼物表。

1   100100  0       1000    10
2   100100  1001    2000    20
3   100100  2001    3000    30
4   100100  3001    4000    40