mysql - 可以加入多个字段吗?

时间:2011-02-02 19:10:41

标签: sql mysql join

我正在尝试编写一个连接语句,但我发现我正在运行的查询为找到的每个标题输出相同的信息。好像我需要在多个字段上连接表格,我不确定是否可能?这有点难以解释,但下面的代码显示了我想要完成的事情以及实际发生的事情......希望有人能指出我正确的方向吗?

+----------------------------------------------------+
TABLE: NODE N
+----------------------------------------------------+
nid   | vid   | type  | language | title      | uid
22196 | 22196 | einfo | en       | Contact 15 |  15
22040 | 22040 | fmp   | en       | John Doe   |  15
22043 | 22043 | fmp   | en       | Jane Doe   |  15

+----------------------------------------------------+
TABLE: CONTENT_FIELD_PN P
+----------------------------------------------------+
vid   | nid   | delta | field_name_nid 
22196 | 22196 |     0 |          22040 
22196 | 22196 |     1 |          22043 


+----------------------------------------------------+
TABLE: CONTENT_FIELD_PP PP
+----------------------------------------------------+
vid   | nid   | delta | field_homephone_value
22196 | 22196 |     0 | 6505551212
22196 | 22196 |     1 | 6505551444

我正在尝试编写一个将产生的连接语句:

+----------------------------------------------------+
TRYING TO OUTPUT
+----------------------------------------------------+
title       | field_homephone_value | delta
John Doe    | 6505551212            | 0
Jane Doe    | 6505551444            | 1

+----------------------------------------------------+

目前的产出是什么

+----------------------------------------------------+
title       | field_homephone_value | delta
John Doe    | 6505551212            | 0
Jane Doe    | 6505551212            | 1

+----------------------------------------------------+
THE QUERY AS IT'S CURRENTLY WRITTEN
+----------------------------------------------------+

SELECT p.field_name_nid, n2.title, p.delta, pp.field_homephone_value
FROM node n 
LEFT JOIN content_field_pn p ON n.nid = p.nid 
LEFT JOIN node n2 ON p.field_name_nid = n2.nid 
LEFT JOIN content_field_pp pp ON p.nid = pp.nid 
WHERE n.nid = 22196 
GROUP BY p.delta

2 个答案:

答案 0 :(得分:15)

您可以在and子句中使用on

LEFT JOIN content_field_pp pp ON p.nid = pp.nid AND p.vid = pp.vid
                                                ^^^^^^^^^^^^^^^^^^

答案 1 :(得分:3)

您可以加入多个领域......

SELECT `blah` FROM `a` LEFT JOIN `b` ON `b`.`id` = `a`.`id` AND `b`.`field2` = `a`.`field2`