2017-10-18 133 views
-2

如何從連接中的選擇字段使用自定義別名字段?如何使用連接中選擇字段的自定義別名字段?

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 
+0

範圍問題。將第一次加入派生表中! – jarlh

回答

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; 

否我用CROSS JOIN替換了INNER JOININNER JOIN沒有ON是沒有意義的。

編輯:

你似乎要測試多個值,從而獲得匹配。你可以嘗試在HAVING條款中進行比較。該條款可以參考SELECT中的列:

SELECT LOWER(CONCAT(ufn.`value`, '.', uln.`value`, CAST(RAND()*1e6 AS UNSIGNED))) AS newlogin 
FROM user_firstname` ufn CROSS JOIN 
    `user_lastname` uln 
WHERE `ufn`.`sex` = 'male' 
HAVING NOT EXISTS (SELECT 1 
        FROM user u 
        WHERE u.login = newlogin 
       ) 
ORDER BY RAND() 
LIMIT 1; 
+0

不可能!謝謝! :) –

+0

戈登剛剛閱讀我的評論... – jarlh

相關問題