我有疑问:
SELECT p.`obj_id` ,
p.`alt_name` ,
o.`name`,
p.`id`,
oc.`text_val`,
oc.`float_val`
FROM `cms3_hierarchy` p
LEFT JOIN `cms3_objects` o
ON p.`obj_id` = o.`id`
LEFT JOIN `cms3_object_content` oc
ON p.`obj_id` = oc.`obj_id`
WHERE (oc.`field_id` = 221 OR oc.`field_id` = 248 )
AND (p.`rel`=903687) LIMIT 0,50
但是这样回答:
obj_id name id 221 248 1 first 2 null 1 first null 3
好吧,我有一个不同值的obj_id。 但对我来说,这看起来像这样:
obj_id name id 221 248 1 first 2 3
怎么做?
答案 0 :(得分:0)
LEFT JOIN
右表上的条件只应在ON
子句中指定,当它们在WHERE
子句中时,连接自动变为INNER JOIN
因为NULL
比较。
另外,使用IN()
将同一列与多个值进行比较,而不是OR
。我还使用MAX()
将行分组为一行,所以:
SELECT p.obj_id , p.alt_name , o.name,p.id,
MAX(CASE WHEN oc.field_id = 221 THEN oc.text_val END) as col_221,
MAX(CASE WHEN oc.field_id = 1123 THEN oc.text_val END) as col_1123,
MAX(oc.float_val)
FROM cms3_hierarchy p
LEFT JOIN cms3_objects o
ON p.obj_id = o.id
LEFT JOIN cms3_object_content oc
ON p.obj_id = oc.obj_id and oc.field_id in(221,248,1123)
WHERE p.rel=903687
LIMIT 0,50
GROUP BY p.obj_id , p.alt_name , o.name,p.id