MySQL查询聚合MAX和子查询

时间:2017-03-29 13:53:20

标签: mysql sql

有没有办法从内部选择的子查询中获取值?

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 @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;

3 个答案:

答案 0 :(得分:1)

你的意思是这样的:

/*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

答案 1 :(得分:0)

根据评论中的新信息更改了答案。听起来您only_full_group_by已启用sql_mode。您的查询可能适用于已禁用的查询,但以下内容也适用于您:

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)
-- ORDER by sl.domain_id DESC LIMIT 1 # Removed in favor of the following line
GROUP BY sl.domain_id HAVING MAX(sl.id)
;

请注意,子查询可能没有返回您想要的stop_domain.id - 您可能打算选择MAX(sd.id),或者您可能只删除了WHERE sd.url='foo'清晰度。

答案 2 :(得分:0)

无需max()

SELECT
  IFNULL(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)
ORDER by sl.id DESC
LIMIT 1