mysql 选择SQL以根据同一表中的某些条件修改输出值

xqkwcwgp  于 2023-04-05  发布在  Mysql
关注(0)|答案(2)|浏览(124)

根据下表:

... |  id    | type | ...
 ... |    1   |  1   | ...
 ... |    1   |  2   | ...
 ... |    1   |  3   | ...
 ... |    1   |  4   | ...
 ... |    2   |  1   | ...
 ... |    2   |  2   | ...
 ... |    3   |  1   | ...
 ... |    3   |  3   | ...
 ... |    4   |  1   | ...
 ... |    5   |  4   | ...

我想写一个选择查询,将返回行,并将返回值从4改为3,如果(相同的id和类型3和4)存在。
注意,如果only type = '4'并且没有(相同id & type = '3')存在,则结果将不会被修改
示例查询无法工作,因为它无法检查上层条件:
SELECT id,CASE WHEN(type = '4')THEN '3' ELSE type end AS type FROM表;
我期望的输出是:

... |  id    | type | ...
 ... |    1   |  1   | ...
 ... |    1   |  2   | ...
 ... |    1   |  3   | ...
 ... |    1   |  3*  | ...
 ... |    2   |  1   | ...
 ... |    2   |  2   | ...
 ... |    3   |  1   | ...
 ... |    3   |  3   | ...
 ... |    4   |  1   | ...
 ... |    5   |  4   | ...
7vhp5slm

7vhp5slm1#

要更新:

UPDATE table
SET type = 3
WHERE id IN (
  SELECT id 
  FROM table t1 
  JOIN table t2 
   ON t1.id = t2.id 
   AND t1.type = 3 
   AND t2.type = 4
) ids

要选择:

SELECT
id,
IF(t.type = 4 AND (IFNULL(ids.id, 0) > 0),3,t.type) as type
FROM table t
LEFT JOIN (
      SELECT id 
      FROM table t1 
      JOIN table t2 
       ON t1.id = t2.id 
       AND t1.type = 3 
       AND t2.type = 4
    ) ids
ON ids.id = t.id
sczxawaw

sczxawaw2#

我有一个,这是很多步骤,但至少是工作。你可以自己简单化。

CREATE TABLE order_items (no INT AUTO_INCREMENT PRIMARY KEY, id INT, type INT);

INSERT INTO order_items(id, type) VALUES(1, 1) ,(1, 2),(1, 3),(1, 4),(2, 1), (3, 4), (4, 1), (4, 4);

SELECT * FROM order_items;

WITH cte AS (
    SELECT no FROM order_items WHERE id IN (SELECT a.id FROM order_items a, (SELECT NO, id FROM order_items WHERE TYPE = 4) b WHERE a.id = b.id  GROUP BY id HAVING COUNT(a.id) > 1) AND TYPE = 4
)
UPDATE order_items
SET order_items.type = 3
WHERE order_items.no IN (SELECT NO FROM cte);

SELECT * FROM order_items;

相关问题