MySQL Query避免使用变量

时间:2017-03-29 22:52:19

标签: mysql

有没有办法将第一个查询放入主查询并避免设置变量?

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

stop_domain

id | url

stop_link

id | duid | domain_id

2 个答案:

答案 0 :(得分:1)

SELECT     IFNULL(MAX(duid), 0) + 1 AS duid
           ,t.id
FROM       (SELECT id FROM stop_domain LIMIT 1) t
INNER JOIN stop_link
ON         domain_id = t.id
GROUP BY   t.id;

答案 1 :(得分:0)

确实有,

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