如何使这个简单的MySQL连接选择?

时间:2011-11-07 13:56:51

标签: php mysql

我有第一张表已注册,此表包含:

uid (int)
email (varchar)
telephone (varchar)

看起来像这样

++++++++++++++++++++++++++++++++++++++++++++++++
+ uid   +  email             + telephone       +
++++++++++++++++++++++++++++++++++++++++++++++++
+ 1    +  david@gmail.com    + 333-111-5555    +
++++++++++++++++++++++++++++++++++++++++++++++++
+ 2    +  erick@gmail.com    + 333-222-5555    +
++++++++++++++++++++++++++++++++++++++++++++++++
+ 3    +  james@gmail.com    + 333-333-5555    +
++++++++++++++++++++++++++++++++++++++++++++++++
+ 4    +  svene@gmail.com    + 333-444-5555    +
++++++++++++++++++++++++++++++++++++++++++++++++
+ 5    +  simon@gmail.com    + 333-555-5555    +
++++++++++++++++++++++++++++++++++++++++++++++++
+ 6    +  peter@gmail.com    + 333-666-5555    +
++++++++++++++++++++++++++++++++++++++++++++++++
+ 7    +  mikka@gmail.com    + 333-777-5555    +
++++++++++++++++++++++++++++++++++++++++++++++++

我有第二个表引荐,此表包含以下列:

id (int)
uid0 (int)
uid1 (int)

第二个表保存id为autoincrement,然后uid0为父用户id,uid1为referer的用户id

它可以包含这些值,例如

+++++++++++++++++++++++
+ id   +  uid0 + uid1 +
+++++++++++++++++++++++
+ 1    +  2    +  3   +
+++++++++++++++++++++++
+ 2    +  2    +  5   +
+++++++++++++++++++++++  

我知道如何在foreach循环中回显来自已注册表的所有已注册的电子邮件和电话。

但是,我需要加入并回复所有与特定用户(uid0)相关的推荐人(uid1)电子邮件。

+++++++++++++++++++++++
+ id   +  uid0 + uid1 +
+++++++++++++++++++++++
+ 1    +  2    +  3   +
+++++++++++++++++++++++
+ 2    +  2    +  5   +
+++++++++++++++++++++++
+ 3    +  4    +  1   +
+++++++++++++++++++++++
+ 4    +  4    +  6   +
+++++++++++++++++++++++
+ 5    +  4    +  7   +
+++++++++++++++++++++++    

因此,最终的回声结果将如下所示:

email                  telephone               referers
erick@gmail.com        333-222-5555            james@gmail.com, simon@gmail.com
svene@gmail.com        333-444-5555            david@gmail.com, peter@gmail.com, mikka@gmail.com

我怎样才能做这个“线程化”的foreach循环?

提前致谢。

1 个答案:

答案 0 :(得分:2)

您可以尝试使用group concat;

进行子选择

类似的东西:

select r.email, r.telephone from registered as r, 
(SELECT 
       GROUP_CONCAT(r.email)
       FROM registered
       GROUP uid1 where uid0 = r.uid)