正确连接3个表


Properly Join 3 Tables

试图自行修复现有代码的错误,而不是由我修复。此代码的错误是,除非相应的id在第二个表中有项目,否则它根本不会显示在输出中。在第一个表(邮件)中,我有多个条目,它们被过滤掉了,但输出中确实显示了正确的邮件总数。。。只是不会输出它,除非邮件在第二个表中有项目。我尝试了另一个使用diff连接的查询

SELECT 
    id, 
    messageType, 
    sender, 
    mail.receiver, 
    subject, 
    body, 
    has_items, 
    money, 
    cod, 
    checked 
FROM 
    mail 
        LEFT OUTER JOIN mail_items 
            ON id = mail_id 
        LEFT JOIN item_instance 
            ON item_guid = guid

问题是…我得到错误:您的SQL语法有错误;查看与MySQL服务器版本对应的手册,了解在"LIMIT 1"附近使用的正确语法

我该怎么做才能使邮件表和mail_items表都加入,同时它正确地从第三个表中获取项目guid,并输出邮件表条目,即使mail_item斯表中没有该邮件的项目。

//==========================$_GET and SECURE=================================
$start = (isset($_GET['start'])) ? $sqlc->quote_smart($_GET['start']) : 0;
if (is_numeric($start)); 
else 
    $start = 0;
$order_by = (isset($_GET['order_by'])) ? $sqlc->quote_smart($_GET['order_by']) : 'id';
if (preg_match('/^[_[:lower:]]{1,12}$/', $order_by)); 
else 
    $order_by = 'id';
$dir = (isset($_GET['dir'])) ? $sqlc->quote_smart($_GET['dir']) : 1;
if (preg_match('/^[01]{1}$/', $dir)); 
else 
    $dir = 1;
$order_dir = ($dir) ? 'ASC' : 'DESC';
$dir = ($dir) ? 0 : 1;
//==========================$_GET and SECURE end=============================
$query = $sql->query("SELECT a.id, a.messageType, a.sender, a.receiver, a.subject, a.body, a.has_items, a.money, a.cod, a.checked, b.item_guid, c.itemEntry
                      FROM mail a INNER JOIN mail_items b ON a.id = b.mail_id LEFT JOIN item_instance c ON b.item_guid = c.guid ORDER BY $order_by $order_dir LIMIT $start, $itemperpage");
$total_found = $sql->num_rows($query);
$this_page = $sql->num_rows($query);
$query_1 = $sql->query("SELECT count(*) FROM `mail`");
$all_record = $sql->result($query_1,0);

我不是SQL大师,但我认为

FROM mail a INNER JOIN mail_items b 

需要AS关键字进行别名分配:

FROM mail AS a INNER JOIN mail_items AS b 

尝试这种类型,从表1中选择*作为T1,在T.id=T2上将表2作为T2。在T2.id=T3上将表3作为T3。id

试试这样的东西:

SELECT 
/*
    The columns that you want to select
*/
FROM 
    mail a
LEFT OUTER JOIN mail_items b ON a.id = b.mail_id 
LEFT JOIN item_instance c ON b.item_guid = c.guid

请注意,当您尝试选择列时,请确保将正确的表别名附加到列名。这里,表mailmail_itemsitem_instance分别具有abc作为它们的别名。

如果您使用上面的查询来保持表的相同别名,则需要对代码执行以下修改:

$order_by = (isset($_GET['order_by'])) ? $sqlc->quote_smart($_GET['order_by']) : 'id';
if (preg_match('/^[_[:lower:]]{1,12}$/', $order_by)); 
else 
    $order_by = 'a.id';