2015-07-10 88 views
0

我試圖從我的數據庫中使用一組測試數據來創建一個隨機名稱生成器查詢。按行合併兩個子查詢

該字段name存儲客戶全名,但我希望查詢從name字段中獲取隨機名並從name字段獲取隨機姓。

查詢:

select concat(first_name, ' ', last_name) from 

((select lcase(SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 1), ' ', -1)) as first_name 
from customers 
where SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 1), ' ', -1) not like '%Mrs' 
and SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 1), ' ', -1) not like '%Mrs' 
and SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 1), ' ', -1) not like '%Mr' 
and SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 1), ' ', -1) not like '%.%' 
and length(SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 1), ' ', -1)) > 1 
order by rand() 
limit 10) as first_name_tbl, 

(select lcase(SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1)) as last_name 
from customers 
where SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1) not like '%Mrs' 
and SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1) not like '%Mrs' 
and SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1) not like '%Mr' 
and SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1) not like '%.%' 
and length(SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1)) > 1 
order by rand() 
limit 10) as last_name_tbl); 

的問題,我的查詢是返回重名,而不是記錄的權數。

目前的結果:

100 rows in set 

| sabrina mole      | 
| daniel mole      | 
| helen mole       | 
| jenny mole       | 
| caroline mole      | 
| catherine mole      | 
| julia mole       | 
| carmella mole      | 
| mark mole       | 
| catharine mole      | 
| sabrina salgado     | 
| daniel salgado      | 
| helen salgado      | 
| jenny salgado      | 
| caroline salgado     | 
| catherine salgado     | 
| julia salgado      | 
| carmella salgado     | 
..... 

期望的結果

10 rows in set 

| sabrina mole      | 
| daniel salgado      | 
| helen oinn       | 
| jenny hird       | 
| caroline thompson     | 
| catherine helena     | 
| julia taylor      | 
| carmella spectrum     | 
| mark storrie      | 
| catharine pat      | 
+0

當你說重名的加入,你的意思,你只希望每個名字和姓氏使用一次? –

+0

@HolmesIV是的,那完全正確。 –

回答

3

的問題是要創建一個使用兩個10排表交叉聯接。

所以10×10 = 100行。

你需要使用一個會話變量的rowid每個表
See rowid on MySql

(SELECT @rowidFirst:[email protected]+1 as rowid, first_name_tbl.* 
    FROM 
    (SELECT ....) as first_name_tbl 
) as firstWithRowID 

(SELECT @rowidLast:[email protected]+1 as rowid, last_name_tbl.* 
    FROM 
    (SELECT ....) as last_name_tbl 
) as lastWithRowID 

然後通過ROW_ID

SELECT * 
FROM firstWithRowID, lastWithRowID 
WHERE firstWithRowID.rowid = lastWithRowID.rowid 
+0

我之前試過類似的東西,問題是如果你使用'rand by()命令',我這樣做是因爲我需要返回的隨機名比rowid不會按正確的順序 –

+0

這個編輯怎麼樣,創建隨機表後添加row_id? –

+0

這是一個好主意,我會試試看,結果回到你身邊 –