mysql 乙個字段儲存多個ID時的查詢

2021-09-02 23:53:37 字數 2162 閱讀 3688

mysql - 乙個字段儲存多個id時的查詢

一、說明

當在一張表的某個欄位中儲存了另外一張表的多個id時常用查詢

二、準備

假設有一部落格,每乙個主題允許有多個類別。資料庫設計時建了類別和主題兩張表,主題對類別的關聯設定在主題表中。

[sql] view plain copy

-- 類別表ddl  

create table `t_categorys` (  

`c_id` int(11) not null,  

`c_name` varchar(255) not null,  

primary key (`c_id`)  

)   

[sql] view plain copy

-- 主題表ddl  

create table `t_topic` (  

`t_id` int(11) not null,  

`t_name` varchar(255) not null,  

`t_categorys` varchar(128) not null,  

primary key (`t_id`)  

)  [sql] view plain copy

-- 準備類別資料  

insert into `t_categorys` (`c_id`, `c_name`) values ('1', 'struts');  

insert into `t_categorys` (`c_id`, `c_name`) values ('2', 'spring');  

insert into `t_categorys` (`c_id`, `c_name`) values ('3', 'ibatis');  

insert into `t_categorys` (`c_id`, `c_name`) values ('4', 'hibernate');  

[sql] view plain copy

-- 準備主題資料  

insert into `xilen_dev`.`t_topic` (`t_id`, `t_name`, `t_categorys`) values ('1', 'ssi整合示例', '1,2,3');  

insert into `xilen_dev`.`t_topic` (`t_id`, `t_name`, `t_categorys`) values ('2', 'ssh整合示例', '1,2,4');  

三、查詢

1、查詢多id的字段中包含某個id的記錄

sql:

[sql] view plain copy

-- 查詢類別包含了ibatis(id=3)的主題記錄  

select * from t_topic where find_in_set(3, t_categorys)  

結果:2、查詢多id欄位中這些id所代表的記錄

sql:

[sql] view plain copy

-- 查詢主題 ssh整合示例(id=2) 包含的類別記錄  

select * from t_categorys c where (select find_in_set(c.c_id,t.t_categorys) from t_topic t where t.t_id=2)  

結果:3、查詢時將多id的字段的id轉換為對應的標識

sql:

[sql] view plain copy

-- 查詢主題表時將類別的id轉換為類別的name  

select t.t_id as topicid,   

(select group_concat(c.c_name) from t_categorys c where find_in_set(c.c_id,t.t_categorys)) as categoryname       

from t_topic t  

結果:4、補充

find_in_set函式預設是以符號 , 作為分割符的,如果多id欄位使用的這個預設的分隔符,而是以如 | 的符號作為分隔符,那麼:

[sql] view plain copy

-- 非 , 作為分隔符時,先replace函式替換它  

select * from t_topic where find_in_set(3, replace(t_categorys,'|',','))  

MySQL 乙個字段儲存多個ID時的查詢

一 說明 當在一張表的某個欄位中儲存了另外一張表的多個id時常用查詢 二 準備 假設有一部落格,每乙個主題允許有多個類別。資料庫設計時建了類別和主題兩張表,主題對類別的關聯設定在主題表中。sql view plain copy 類別表ddl create tablet categorys c idi...

mysql多表乙個字段

先執行這三個 show variables like group concat max len 查詢大小 set global group concat max len 10240000 設定大小滿足執行後能夠存放所有的插入語句 set session group concat max len 10...

mysql乙個欄位為空時使用另乙個字段排序

表中有兩個日期欄位createdate,updatedate。其中updatedate可以為空,要求使用updatedate排序,如果updatedate為空則使用createdate排序,結果要順序排下來。按照常規方法 這樣的結果是為空的資料排在了最下面,不符合要求。這樣試試 這樣排的結果是先按u...