有没有一种方法可以从子查询中的select内部位置获取价值?

stop_link表

id | duid | domain_id
1  | 1    | 1
2  | 2    | 1
3  | 1    | 2
4  | 2    | 2
5  | 3    | 1


我想要的结果(假设domain_id = 2)

duid    | domain_id
3       | 2


查询(不起作用):

INSERT INTO stop_link (
              duid,

              domain_id)
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)


查询工作,但我希望避免使用Set Variable:

SET @domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1);
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid
  , @domain_id
FROM
  stop_link sl
WHERE sl.domain_id = @domain_id;

最佳答案

您的意思是这样的吗:

/*Your example Table*/

DECLARE @T
TABLE(ID INT,duid INT,domain_id INT)

INSERT INTO @T
VALUES
(1 , 1    , 1 ),
(2  , 2    , 1),
(3  , 1    , 2),
(4  , 2    , 2),
(5  , 3    , 1)

--The query
SELECT domain_id,Isnull(max(duid),0)+1 [newId]
FROM @T
GROUP BY domain_id

关于mysql - MySQL查询聚合MAX和子查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43095544/

10-10 05:03