mysql多表查詢方式 MySQL多表查詢方式問題

2021-10-17 23:50:25 字數 1852 閱讀 4705

你的 sql 沒有用到任何索引,對 a b 兩個表都是全表掃瞄,在資料量小的時候是沒有問題的,但是如果資料量超過 100 萬,效能問題就會突顯出來。

這裡不清楚你的 created_at 欄位是什麼型別,不過從你的** date_format(created_at, '%y-%m-%d') 看來,應該是 datetime 或者 timestamp,這個欄位對你的場景來說並不是很友好,如果是我的話,可能會新增乙個 date 型別的字段 created_at_date 來解決這個問題:

alter table `a` add column `created_at_date` date;

alter table `b` add column `created_at_date` date;

alter table `a` add index `created_at_date` (`created_at_date`);

alter table `b` add index `created_at_date` (`created_at_date`);

對錶中現有的資料,將 created_at_date 設定為 date(created_at):

update `a` set `created_at_date` = date(`created_at`);

update `b` set `created_at_date` = date(`created_at`);

如果不想改應用層**,可以建立乙個 trigger,自動設定該欄位。

其次,不太清楚你的具體需求,不知道是日期出現一次就統計一次,還是只要表中存在該日期,就算一次?如果是情況二,樓上的回答其實就可以了,可以用到 date 列的索引:

select c.t,count(*) from (

select a.t,count(*) from a a group by a.t

union all

select b.t,count(*) from b b group by b.t

) cgroup by c.t;

如果是情況一,從你寫的 sql 判斷可能是這種情況吧。這時要把兩個臨時表的 date 列拿出來做 full outer join 了,然後計算 a.count + b.count。但是 mysql 不支援 full outer join,可以 用 left outer join union right outer join 小技巧 來解決,完整的 sql 如下(僅供參考):

select ta.`created_at_date`, ta.c + ifnull(tb.c,0) cnt from

select `created_at_date`, count(*) c from a group by `created_at_date`

) as ta left outer join

select `created_at_date`, count(*) c from b group by `created_at_date`

) as tb on ta.`created_at_date` = tb.`created_at_date`

union

select tb.`created_at_date`, tb.c cnt from

select `created_at_date`, count(*) c from a group by `created_at_date`

) as ta right outer join

select `created_at_date`, count(*) c from b group by `created_at_date`

) as tb on ta.`created_at_date` = tb.`created_at_date`

where ta.c is null

mysql多表 MySQL 多表查詢

多表查詢 select listname from tablename1,tablename2 笛卡爾積 多表查詢中,如果沒有連線條件,則會產生笛卡爾積 數學中的定義 假設集合a 集合b 則兩個集合的笛卡爾積為 實際執行環境下,應避免使用笛卡爾積 解決方案 在where加入有效的連線條件 等值連線 ...

mysql 多表查詢or MySQL 多表查詢

前期準備 建表create table dep id int,name varchar 20 create table emp id int primary key auto increment,name varchar 20 enum male female not null default ma...

mysql 多表查詢

分享主題 mysql多表查詢 本庫中表 act promotion item left join select a.act id,a.act name,p.prmotion desc from act a left join promotion p on a.act id p.act id 查詢活動...