如何优化此VIEW声明?

时间:2011-07-07 14:31:38

标签: mysql sql view query-optimization

我有一个VIEW,它很慢。我不喜欢VIEW语句,因为有很多JOINSUNION

这是视图声明。

Create VIEW NewView AS

SELECT t2.* FROM Table1 t1
JOIN Table2 t2
ON t1.Column1 = t2.Column1 AND t1.Column2 = t2.Column2
WHERE t1.Column3 !='String'

UNION

SELECT t1.*, 'Add this string to the Last Column' FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.Column1 = t2.Column1 AND t1.Column2 = t2.Column2
WHERE t2.Column1 is null OR t1.Column3 ='String'
ORDER BY Column 4

基本上,我们的想法是,如果Table1Table2中存在记录,Table2的记录应覆盖Table1的记录。我该如何优化呢?

我在两个表中都有一个主键id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,但我不确定如何将其与视图集成。我希望视图有一个主键或复合键。我不能使用其他列,因为所有列都可以具有null和重复值。

3 个答案:

答案 0 :(得分:3)

您可以使用外部联接加入和比较,然后使用COALESCE优先选择T2到T1。

要保留一个唯一的密钥,并假设您的ID都是正面的,您可以使一个表的ID为负数。

SELECT
  COALESCE(t2.id,     -t1.id)      AS id,
  COALESCE(t2.Column1, t1.Column1) AS Column1,
  COALESCE(t2.Column2, t1.Column2) AS Column2
FROM
  Table1          AS t1
FULL OUTER JOIN
  Table2          AS t2
    ON  t1.Column1 = t2.Column2
    AND t1.Column2 = t2.Column2
WHERE
  COALESCE(t2.Column3, t1.Column3) = 'String'

修改

有关选择哪个表具有预测性的更复杂规则,您可以使用CASE语句...

(这与上面相同,但可以针对不同的预测规则进行修改。)

SELECT
  CASE WHEN t2.id IS NULL THEN -t1.id      ELSE t2.id      END  AS id,
  CASE WHEN t2.id IS NULL THEN  t1.Column1 ELSE t2.Column1 END  AS Column1,
  CASE WHEN t2.id IS NULL THEN  t1.Column2 ELSE t2.Column2 END  AS Column2
FROM
  Table1          AS t1
FULL OUTER JOIN
  Table2          AS t2
    ON  t1.Column1 = t2.Column2
    AND t1.Column2 = t2.Column2
WHERE
  COALESCE(t2.Column3, t1.Column3) = 'String'

答案 1 :(得分:2)

如果您确定没有重复项,那么您可以通过UNION替换UNION ALL来增强它ALL如果没有{{1}},查询结果将被排序并重复UNIONing时将被删除。见http://dev.mysql.com/doc/refman/5.0/en/union.html

答案 2 :(得分:0)

这应该是这样的:

SELECT 
    IFNULL(t2.Col1, t1.Col1) Col1,
    IFNULL(t2.Col2, t1.Col2) Col2,
    IFNULL(t2.Col3, t1.Col3) Col3,
    IFNULL(t2.Col4, t1.Col4) Col4,
    'Add this string to the Last Column' 
FROM 
    Table1 t1
    LEFT JOIN Table2 t2 ON t1.Column1 = t2.Column1 AND t1.Column2 = t2.Column2
WHERE 
    t1.Column3 ='String'
ORDER BY 
    Col4

如果table2列在数据库中可以有正常的NULL值,那么这个SELECT应该像这样开始:

SELECT 
    IF(t2.id is NULL, t1.Col1, t2.Col1) Col1,
    IF(t2.id is NULL, t1.Col2, t2.Col2) Col1,
    IF(t2.id is NULL, t1.Col3, t2.Col3) Col1,
    IF(t2.id is NULL, t1.Col4, t2.Col4) Col1,
    'Add this string to the Last Column' 
    .
    .