SQL語句優化 in 改寫成join 、1對多取出1對1、笛卡爾積、 where is null 、NULL導致not in寫法不對、行號問題


x.a必須是唯一的,才能改寫成join的語句。

select * from x where a in (select a from y );

select  distinct x.* from x join y  on x.a=y.a;

已經能滿足大多數場景。

二、一對多

only_full_group_by

研發提供的錯誤寫法

   SELECT
Openid,
max(OperateTime),
      SourceIndex
FROM
A
GROUP BY
Openid;

由於group by 中只有Openid,sql_mode如果嚴格,執行是不成功的。

正確語句如下:

 

select * from A  where (Openid,OperateTime) in (select Openid,max(OperateTime) from  A  group by Openid);

########################################################################################

兩張表1對多,取出1對1的信息

 

 

where lie is null  ,不要用and lie is null

###########################################

笛卡爾積:

select * from a,b; 沒有條件

########################################

 

 

 

為什么列里不讓有NULL,NULL會導致查詢not in 查出來的數據有問題。

正確的寫法:

select * from a where id not in (select id from b where id is not null );

######################################################################

 行號:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM