Mysql(6)2つのテーブル間のクエリーと更新を初級的に使用

6702 ワード

1.A表のデータを整理してB表に入れる:
count()は集約関数です.テーブルのすべてのレコード数を求めるselect*fromテーブル名クエリーテーブルのすべてのレコードselect count(*)fromテーブル名クエリーテーブルのすべてのレコード数です.
insert into tableB(service_user,count) select service_user,count(service_user) from tableA group by service_user;
SELECT counter,count(counter) FROM think_qoe_service_user GROUP BY counter;

2.クエリー:別のテーブルに記録されないテーブルがある
テキスト
A,Bの2つの表、IDフィールドの中で、A表が存在するがB表が存在しないデータを探し出す:
方法1:効率が低い
select distinct A.ID from A where A.ID not in (select ID from B);

方法二:効率が中等である
left join...on...「B.ID isnull」を使用すると、左接続後にB.IDフィールドがnullのレコードleft join:右テーブルに一致するローがなくても、左テーブルからすべてのローが返されます.
select A.ID from A left join B on A.ID=B.ID where B.ID isnull

方法3:(速度が最も速い)
select * from B where (select count(1) as num from A where A.ID=B.ID ) =0

count(1):最初の行の列数(つまりデータのレコード数)count(*):データのレコード数も計算され、どのフィールドに指定するかが自動的に最適化されます.
具体的には、
同じサービスが2つのテーブルに存在します.userのレコード
1.inで
select service_user from A where A.service_user in ( select distinct service_user from B )

0.14s
2.left joinで
select service_user from A left join B on A.service_user=B.service_user where B.service_user is not null

0.356 sで、結果は混乱していて、続けられませんでした.
3.内部もwhere
select service_user from A where ( select count(1) from B where A.service_user=B.service_user )>0

0.401s
1つのテーブルのデータで別のテーブルを更新します(同じテーブルは同じです)
UPDATE 
QQQ Q,
YYY Y
SET
Q.id=Y.id
WHERE Y.SERVICE_USER=Q.SERVICE_USER
#       group by     ,        (      A   )
UPDATE bbb B, ( SELECT A.SERVICE_USER,count(*) c FROM aaa A GROUP BY A.SERVICE_USER )C SET B.USER_NUM=C.c WHERE B.SERVICE_USER=C.SERVICE_USER
#                  
UPDATE
aaa A,
(
SELECT
A.SERVICE_USER,count(*) c
FROM
aaa A           #     A
GROUP BY A.SERVICE_USER
)C
SET
A.USER_NUM=C.c
WHERE
A.SERVICE_USER=C.SERVICE_USER

同じテーブルの重複データの削除
delete FROM userinfoJiNan where userid not in ( select * FROM ( select max(userid) u from userinfoJiNan group by userid )B ) #  not in             , :where userid not in (...)C      #mysql              (  ),         #         ,     userid,    select * from ( select id from userinfoJiNan group by userid )    where id not in ...