有没有更好的方法来进行查询?

时间:2017-10-07 15:05:44

标签: sql sql-server optimization

这是我的sql,但我觉得它太复杂了,也许它不是非常快速有效?我对吗?还是有更好的方法?

SELECT  TEventInfoid ,A.TTNum,
    CASE WHEN TModelid = 3822 THEN ( SELECT title
                                     FROM   dbo.sns_event WHERE id=TEventInfoid
                                   )
         ELSE ( SELECT  name
                FROM    dbo.sns_exhibition WHERE id=TEventInfoid
              )
    END,
    CASE WHEN TModelid = 3822 THEN ( SELECT start_time
                                     FROM   dbo.sns_event WHERE id=TEventInfoid
                                   )
         ELSE ( SELECT  start_Time
                FROM    dbo.sns_exhibition WHERE id=TEventInfoid
              )
    END,
    CASE WHEN TModelid = 3822 THEN ( SELECT [address]
                                     FROM   dbo.sns_event WHERE id=TEventInfoid
                                   )
         ELSE ( SELECT  [address]
                FROM    dbo.sns_exhibition WHERE id=TEventInfoid
              )
    END
   FROM    
       T_Ticktets A
   WHERE A.TTNum='100229143644'

3 个答案:

答案 0 :(得分:1)

你可以使用它。

    $scope.blurFunc = function(){
    $scope.showInput = true;
  }

答案 1 :(得分:1)

使用LEFT JOIN

SELECT t.TEventInfoid, t.TTNum,
       (CASE WHEN t.TModelid = 3822 THEN e.title ELSE ex.name END),
       (CASE WHEN t.TModelid = 3822 THEN e.start_time ELSE ex.start_time END),
       (CASE WHEN t.TModelid = 3822 THEN e.address ELSE ex.address END)
FROM T_Ticktets t LEFT JOIN
     dbo.sns_event e
     ON e.id = t.TEventInfoid LEFT JOIN  -- unclear which table which is in
     dbo.sns_exhibition ex
     ON ex.id = t.TEventInfoid AND
        e.id IS NULL                     -- unclear which table which is in
WHERE t.TTNum = '100229143644';

注意:join条件可能包含错误的表格。目前还不清楚哪个列在哪个表中。

此外,如果将TTNum声明为大整数或数字,则可以在要比较的值周围删除单引号。

此版本 做出假设。它假定给定id other 表中没有多行。如果是这种情况,调整查询就不会太难了。

编辑:

解决最后一个问题的方法很简单:

SELECT t.TEventInfoid, t.TTNum,
        COALESCE(e.title, ex.name),
        COALESCE(e.start_time, ex.start_time),
        COALESCE(e.address, ex.address)
FROM T_Ticktets t LEFT JOIN
     dbo.sns_event e
     ON e.id = t.TEventInfoid AND t.TModelid = 3822 LEFT JOIN  -- unclear which table which is in
     dbo.sns_exhibition ex
     ON ex.id = t.TEventInfoid AND t.TModelid <> 3822          -- unclear which table which is in
WHERE t.TTNum = '100229143644';

这可能是查询的最佳形式。注意:如果TModelid可以是NULL,则必须在第二个ON条件中考虑到这一点。

答案 2 :(得分:1)

你怎么对自己这么说?我想要票证模型ID为3822的所有事件以及不是3822的所有展品。

SELECT A.TEventInfoid,
A.TTNum,
e.Title,
e.start_time,
e.[address],
A.TModelid
FROM T_Ticktets A 
JOIN dbo.sns_event e
ON A.id = e.TEventInfoid
WHERE A.TTNum='100229143644'
AND A.TModelid = 3822

UNION ALL

SELECT A.TEventInfoid,
A.TTNum,
e.Name   
e.start_time,
e.[address],
A.TModelid
FROM T_Ticktets A 
JOIN dbo.sns_exhibition e
ON e.id = A.TEventInfoid
WHERE A.TTNum='100229143644'
AND A.TModelid <> 3822