如何使用连接中选择字段的自定义别名字段?

时间:2017-10-18 18:15:50

标签: mysql sql

如何使用联接中选择字段的自定义别名字段?

SELECT LOWER(CONCAT(`ufn`.`value`, '.', `uln`.`value`, CAST(RAND()*1e6 AS UNSIGNED))) AS `newlogin`
FROM `user_firstname` AS `ufn`
INNER JOIN `user_lastname` AS `uln`
LEFT JOIN `user` AS `u` ON `u`.`login` = `newlogin`
WHERE `ufn`.`sex` = 'male' AND `u`.`id` IS NULL
ORDER BY RAND()
LIMIT 1

结果:sql-error.png

编辑:

我的解决方案,但是,......:

SELECT @newlogin
FROM (
    SELECT @newlogin := LOWER(CONCAT(`ufn`.`value`, '.', `uln`.`value`, CAST(RAND()*1e6 AS UNSIGNED)))
    FROM `user_firstname` AS `ufn`
    INNER JOIN `user_lastname` AS `uln`
    WHERE `ufn`.`sex` = 'male'
    ORDER BY RAND()
    LIMIT 1
) AS `ufnX`
LEFT JOIN `user` AS `u` ON `u`.`login` = @newlogin
WHERE `u`.`id` IS NULL

1 个答案:

答案 0 :(得分:1)

在子查询中创建新登录并将其加入:

SELECT LOWER(CONCAT(`ufn`.`value`, '.', `uln`.`value`, nl.num)) AS newlogin
FROM (SELECT CAST(RAND()*1e6 AS UNSIGNED))) AS num
     ) nl CROSS JOIN
     `user_firstname` ufn CROSS JOIN
     `user_lastname` uln LEFT JOIN
     `user` u
     ON `u`.`login` = LOWER(CONCAT(ufn.`value`, '.', uln.`value`, nl.num))
WHERE `ufn`.`sex` = 'male' AND `u`.`id` IS NULL
ORDER BY RAND()
LIMIT 1;

注意我已将INNER JOIN替换为CROSS JOIN。没有INNER JOIN的{​​{1}}毫无意义。

编辑:

您似乎想要测试多个值以获得匹配。您可以尝试将比较放在ON子句中。该子句可以引用HAVING中的列:

SELECT