联合运营商

时间:2017-01-31 10:09:43

标签: mysql sql

我必须从3个表中选择数据。我在第一个和第二个表之间使用INNER JOIN从第二个表中获取另一个字段。但如果不匹配,我必须将其替换为另一个第一个表字段。我正在使用下面的查询,但处理时间太长。是否有另一种方法可以做到这一点

SELECT tba.field, tba.field1, tba.field2 AS test FROM tablea tba
   WHERE tba.field NOT IN (SELECT ta.field FROM tablea ta INNER JOIN tableb tb ON ta.field = tb.field)
UNION
SELECT ta.field, ta.field1, tb.field2 AS test FROM tablea ta
     INNER JOIN tableb tb ON ta.field = tb.field
UNION
SELECT tc.field, tc.field1, tc.field2 AS test FROM tablec tc

SQL fiddle

2 个答案:

答案 0 :(得分:0)

试试这个:这里是查询一的替代方法,如果数据不重复,您也可以使用//example with Slim PHP framework $body = json_decode($app->request->getBody(), true); echo $body["username"]; 代替UNION ALLUNION相对更快

UNION ALL

答案 1 :(得分:0)

这样的事情就足够了:

SELECT tba.field, tba.field1, COALESCE(tb.field2, tba.field2) AS test 
FROM tablea tba
LEFT OUTER JOIN tableb tb ON  tba.field = tb.field
UNION
SELECT tc.field, tc.field1, tc.field2 AS test FROM tablec tc