使用PHP / MySQL连接2个包含多列的表

时间:2014-08-19 10:18:51

标签: php mysql performance join

我承认,我在JOIN条件下有点弱。我想从2个表中获得一个包含4个匹配列的结果集。

我已尝试过下面的代码,但我不确定它是否正确,因为目前我有3-4条记录(结果是正确的)。但是将来可能会有N条记录,因此我需要一个更安全,更安全的查询。

这两个表是:TABLEA和TABLEB

TABLEA

id|pid|nid|sid|name|
--------------------
1 | 2 | 2 | 3 | test
2 | 2 | 2 | 3 | t2 
3 | 2 | 2 | 4 | t3

TABLEB

id|pid|nid|sid|marked |
-----------------------------
1 | 2 | 2 | 3 |  y
2 | 2 | 2 | 3 |  y
3 | 2 | 2 | 4 |  n

以下是我尝试的查询:

SELECT 
    b.marked 
FROM 
    TABLEA AS a
LEFT JOIN 
    TABLEC AS c ON a.id = c.id
LEFT JOIN  
    TABLEB AS b ON ( 
        a.id = b.id
        AND  a.pid = b.pid
        AND  a.nid = b.nid
        AND  a.sid = b.sid  
    )

我收到了预期的结果,但我不确定上面的查询是否适合更大量的记录。

1 个答案:

答案 0 :(得分:0)

你能尝试这样吗

SELECT b.marked from TABLEA as a
LEFT JOIN TABLEC as c on a.id = c.id
LEFT JOIN  TABLEB as b1 ON a.id = b1.id
LEFT JOIN  TABLEB as b2 ON a.pid = b2.pid
LEFT JOIN  TABLEB as b3 ON a.nid = b3.nid
LEFT JOIN  TABLEB as b4 ON a.sid = b4.sid