SQL 兩表一對多關聯,主表某字段保存所有關聯的id


表 a, b

CREATE table a (
    id int,
    name varchar(20),
    age int 
);

CREATE table b (
    id int,
    aids varchar(50),
    name varchar(20),
    age int 
);
表a
id name age
1 a 11
2 b 22
3 c 33
4 a 11

     

表b
id aids name age
1 1,4 a 11
2   b 22

 

1、查詢操作

一、查詢表a 中 name、age的字段值和表b 一樣的 id,select 結果 單行展示:返回一條記錄(id多個時以逗號隔開),為更新服務

-- mysql
select 
(
    select 
    -- group_concat([DISTINCT] a.id [order by a.id asc] [separator ','])  默認逗號分隔
    group_concat(a.id)
    from a
    where a.name=b.name and a.age=b.age
    group by a.name, a.age
) 
from b   
where b.id=1
-- 結果: 1,4
-- oracle
select 
(
    select 
    (listagg(a.id,',') within group (order by a.id))
    from a
    where a.name=b2.name and a.age=b2.age
) 
from b b2
where b.id=1

二、根據表b 的 aids 字段值查詢表a的數據

1、aids 為多個,select 結果 多行展示

mysql 借鑒鏈接:https://blog.csdn.net/a2899202/article/details/101438213

-- mysql
SELECT id,
substring_index( substring_index( aids, ',', b.help_topic_id + 1 ), ',',- 1 ) aid
FROM b 
JOIN mysql.help_topic b ON b.help_topic_id < ( length( aids ) - length( REPLACE ( aids, ',', '' ) ) + 1 ) 
ORDER BY id
-- oracle
select * from (
    SELECT DISTINCT id,to_char(REGEXP_SUBSTR(aids, '[^,]+', 1, LEVEL, 'i')) AS STR FROM b
    CONNECT BY LEVEL <= length(replace(aids,','))
) tmp
where tmp.STR is not null

 2、查詢

-- mysql
select * from a
where id in (
    SELECT 
    substring_index( substring_index( aids, ',', b.help_topic_id + 1 ), ',',- 1 ) aid
    FROM b 
    JOIN mysql.help_topic b ON b.help_topic_id < ( length( aids ) - length( REPLACE ( aids, ',', '' ) ) + 1 ) 
    where id = 1
)
-- oracle
select * from a
where id in (
    SELECT DISTINCT to_char(REGEXP_SUBSTR(aids, '[^,]+', 1, LEVEL, 'i')) AS STR FROM b
    WHERE ID = 1
    CONNECT BY LEVEL <= length(replace(aids,','))
)

2、更新操作

mysql

update b b1 set b1.aids=
(
  -- 沒加這層select 執行SQL語句時會報錯。原因是在更新這個表和數據時又查詢了它,而查詢的數據又做了更新的條件。
    select rp from (
        select 
        (
            select 
            group_concat(a.id separator ',')
            from a
            where a.name=b2.name and a.age=b2.age
            group by a.name, a.age
        ) rp, b2.*
        from b b2    
    ) tmp
    where b1.id=tmp.id
)

 oracle

update b b1 set b1.aids=
(
    select 
    (
        select 
        (listagg(a.id,',') within group (order by a.id))
        from a
        where a.name=b2.name and a.age=b2.age
        group by a.name, a.age
    ) 
    from b b2    
    where b1.id=b2.id
)

 


免責聲明!

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



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