简体   繁体   中英

sql insert into, select, where statement

I want to copy all row from hk_room table into hk_history except row with rStatus = '-' OR rStatus='Long Stay' and rStatus = 'Check Out'.

'-' is the default value for rStatus attribute.

I have tried these two query:

INSERT INTO hk_history
(rNo,rStatus,bs,bq,hk,ds,dq,pc,twl,fm,amt,db,mw,hkR,fo_R,svR,rDate)
SELECT rNo,rStatus,bs,bq,hk,ds,dq,pc,twl,fm,amt,db,mw,hkR,fo_R,svR,rDate
FROM hk_room1;
WHERE rStatus <> '-';

or

INSERT INTO hk_history
(rNo,rStatus,bs,bq,hk,ds,dq,pc,twl,fm,amt,db,mw,hkR,fo_R,svR,rDate)
SELECT rNo,rStatus,bs,bq,hk,ds,dq,pc,twl,fm,amt,db,mw,hkR,fo_R,svR,rDate
FROM hk_room1;
WHERE rStatus = 'Long Stay' AND rStatus = 'Check Out';

but I got this error

INSERT INTO hk_history
 (rNo,rStatus,bs,bq,hk,ds,dq,pc,twl,fm,amt,db,mw,hkR,fo_R,svR,rDate)
 SELECT rNo,rStatus,bs,bq,hk,ds,dq,pc,twl,fm,amt,db,mw,hkR,fo_R,svR,rDate
 FROM hk_room1
 WHERE rStatus IN ( '-', 'Long Stay' , 'Check Out')
 ;

This should help

You have a semicolon before the where in the first query:

INSERT INTO hk_history
    (rNo,rStatus,bs,bq,hk,ds,dq,pc,twl,fm,amt,db,mw,hkR,fo_R,svR,rDate)
    SELECT rNo,rStatus,bs,bq,hk,ds,dq,pc,twl,fm,amt,db,mw,hkR,fo_R,svR,rDate
    FROM hk_room1;
    -------------^
    WHERE rStatus <> '-';

You need to remove it.

To achieve this:

want to copy all row from hk_room table into hk_history except row with rStatus = '-' OR rStatus='Long Stay' and rStatus = 'Check Out'.

Just use a single statement:

INSERT INTO hk_history
    (rNo,rStatus,bs,bq,hk,ds,dq,pc,twl,fm,amt,db,mw,hkR,fo_R,svR,rDate)
    SELECT rNo,rStatus,bs,bq,hk,ds,dq,pc,twl,fm,amt,db,mw,hkR,fo_R,svR,rDate
    FROM hk_room1
    WHERE NOT (rStatus = '-' OR 
               rStatus = 'Long Stay' and rStatus = 'Check Out'
              );

You can also phrase that as:

    WHERE rStatus <> '-' AND
          (rStatus <> 'Long Stay' OR rStatus <> 'Check Out')

However, the previous version seems clearer for your intent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM