从mySQL数据库中读取多个表?

时间:2013-07-02 17:39:16

标签: php mysql

嗯,我对标题中的问题并不十分具体,请原谅我。

我制作了一个.php脚本,它读取数据库中的数据并将其打印到页面上的表格中。基本上它应该作为禁令。但我遇到了一个问题。由于禁令在数据库中的几个不同的表中排序,我需要阅读所有这些表,以获取我在banlist中需要的具体细节。我完成了大部分工作,但是我无法得到禁止“骗子”的管理员的名字。以下是“admin_id”位于“惩罚”表中并且admin的名称位于“clients”表中的方式。现在我无法弄清楚如何通过“惩罚”表中的“admin_id”从“客户”表中获取管理员的名称,并将其打印在同一页面上。

所以this就是我所做的,我只是错过了“管理员”的名字。

以下是从数据库中读取当前信息的代码。

mysql_query("SELECT penalties.id, penalties.type, penalties.time_add, penalties.time_expire,
                    penalties.reason, penalties.inactive, penalties.duration, penalties.admin_id,
                    target.id as target_id, target.name as target_name, target.ip as target_ip 
             FROM penalties, clients as target 
             WHERE (penalties.type = 'TempBan' OR penalties.type = 'Ban')
                  AND inactive = 0 
                  AND penalties.client_id = target.id
             ORDER BY penalties.id DESC") 
  or die(mysql_error());

2 个答案:

答案 0 :(得分:1)

这应该指向正确的方向:

SELECT 
penalties.id, penalties.type, penalties.time_add, penalties.time_expire, penalties.reason, penalties.inactive, penalties.duration, penalties.admin_id, 
clients.id as target_id, clients.name as target_name, clients.ip as target_ip 
FROM penalties 
LEFT JOIN clients
ON penalties.client_id = clients.id 
WHERE (penalties.type = 'TempBan' OR penalties.type = 'Ban')  AND inactive = 0
ORDER BY penalties.id DESC

答案 1 :(得分:0)

你有两个从惩罚到客户的逻辑联接。因此你需要两个连接回来。一个用于“目标”,一个用于“管理员”

SELECT penalties.id, penalties.type, penalties.time_add, penalties.time_expire, penalties.reason, 
       penalties.inactive, penalties.duration, penalties.admin_id, target.id as target_id, 
       target.name as target_name, target.ip as target_ip,
       admin.name
FROM penalties, clients as target, clients as admin

WHERE (penalties.type = 'TempBan' OR penalties.type = 'Ban')  
  AND inactive = 0 
  AND penalties.client_id = target.id 
  AND penalties.admin_ID = admin.id

ORDER BY penalties.id DESC