SQL查询优化加入union不同

时间:2017-01-11 21:05:49

标签: mysql query-optimization

我有一个问题:

Select A.col1 as col1, B.col5 as col2, C.col10 as col3
    FROM Table A 
    JOIN Table B on(A.col2 = B.col2)
    JOIN table C on(C.col1 = B.col3)
UNION
SELECT A.col1 as col1, B.col5 as col2, NULL as col3
     FROM Table A 
     JOIN Table B on (A.col2 = B. col2) 
           where A.col4 != 'somevalue' 

任何使这更快的方法??

Table A
--------
col1         col2          col4
gerry          1           'somevalue'
harry          2           'othervalue'
 tom           3           
sarah          4           'somevalue'

col2 of table A is the primary key

Table B
-------
col2         col3    col5
 1            45      34
 1            34      23
 1            56      67
 2            34      56
 Primary key of B is (col2, col3)
Table C
-------
col1     col10
 34       'heyya'
 467      'tyga'
 56       'pity'

C的主键也是复合键。其中一个键是 col1

 Output:
 col1     col2    col3
 gerry    23       'heyya'
 gerry    67       'pity'
 gerry    34        NULL
 harry     56      'heyya'

因此B的值存在于C中或具有“某些值”。在A中被称为。同时也称为具有两者的值。

1 个答案:

答案 0 :(得分:1)

这对你好吗?所以你得到所有行,如果A.col4<> 'somevalue'然后你得到col3的空白

Select
      A.col1 as col1
    , B.col5 as col2
    , C.col10 as col3
    , if(A.col4 != 'somevalue', 1, 0) as col4
FROM Table A 
JOIN Table B on(A.col2 = B.col2)
    JOIN table C on(C.col1 = A.col3);