mysql加入两个表

时间:2011-04-25 10:59:03

标签: php mysql join

table user:
id_u*   f_name   l_name
----------------------
1       andi     mitchel
2       sarah    bench
3       kirsty   larx

table voucher:
id_v*   id_user    id_target
1       1          2
2       2          3

非常混淆如何将这些表与两个外键连接

$db->query("SELECT * FROM voucher v 
LEFT JOIN user u ON u.id_u = v.id_user
LEFT JOIN user u1 ON u1.id_u = v.id_target
WHERE .... ")

回显while循环...并且什么都不返回?

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
   echo  $r['u.f_name'];
   echo  $r['u1.f_name'];
endwhile;

4 个答案:

答案 0 :(得分:2)

您的JOIN似乎绝对正确。唯一的问题是您已加入表user两次,因此您的列名称相同(例如f_name)。数据库将为这些列分配不同(但任意)的名称。您可以使用AS关键字覆盖此行为:

$db->query("SELECT v.*
                 , u.f_name AS user_f_name
                 , u.l_name AS user_l_name
                 , ta.f_name AS target_f_name
                 , ta.l_name AS target_l_name
            FROM voucher v 
            LEFT JOIN user u ON u.id_u = v.id_user
            LEFT JOIN user ta ON ta.id_u = v.id_target
            WHERE .... ")

然后:

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
   echo  $r['user_f_name'];
   echo  $r['target_f_name'];
endwhile;

我认为你可以用(内部)LEFT JOIN替换JOIN s。除非您的id_userid_target值引用了不存在的用户ID(id_u)。

答案 1 :(得分:1)

看起来你要求所有在凭证表中的人,无论他们是在第1位(用户)还是位置2(目标)......然后,显示该人的姓名。

此查询对每个可能的人及其位置基础(通过WhichPosition)进行预查询。

SELECT STRAIGHT_JOIN
      AllVoucherUsers.WhatPosition,
      u.*
   FROM
      ( select distinct 
              v.id_user, 
             '1' as WhatPosition
           from voucher v
        union select distinct
             v.id_target as id_user,
             '2' as WhatPosition
           from voucher v
      ) AllVoucherUsers
      join users u
         on AllVoucherUsres.id_user = u.id_u

如果你只想要一个给定人的一个实例 - 无论他们的位置如何,只需删除所有“WhatPosition”引用的实例......

SELECT STRAIGHT_JOIN
      u.*
   FROM
      ( select distinct 
              v.id_user
           from voucher v
        union select distinct
             v.id_target as id_user
           from voucher v
      ) AllVoucherUsers
      join users u
         on AllVoucherUsres.id_user = u.id_u

答案 2 :(得分:0)

SELECT * FROM voucher v 
    LEFT JOIN user u ON u.id_u = v.id_user OR u.id_u = v.id_target
    WHERE .... 

答案 3 :(得分:-1)

怎么样: SELECT * FROM凭证JOIN用户ON id_user = id_u

更简单:

SELECT * FROM凭证,用户WHERE id_user = id_u