合并两个子查询的行到行

时间:2015-07-10 18:23:00

标签: mysql sql

我正在尝试使用我的数据库中的一组测试数据创建随机名称生成器查询。

字段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                      |

1 个答案:

答案 0 :(得分:3)

问题是您正在创建一个包含两个10行表的交叉连接。

所以10 x 10 = 100行。

您需要对每个表使用会话变量rowid See rowid on MySql

( SELECT @rowidFirst:=@rowidFirst+1 as rowid, first_name_tbl.*
  FROM  
    ( SELECT .... ) as first_name_tbl
) as firstWithRowID

( SELECT @rowidLast:=@rowidLast+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