简体   繁体   中英

MySQL select from two tables where one column contain 2 variables

I have two tables :

The first table is tbl_ccompany

db_id   db_cname
 1         xxx
 2         yyy

The second table tbl_marketing

db_mid db_name db_ccompany
1       ggg     1,2

In tbl_marketing db_ccompany contain the id of the first table

I want to select the db_cname to print the out put will be like this

1  ggg xxx,yyy

I try the left join between this two table but only i receive the first name

select 
marketing.*,
ccompany.db_cname
from tbl_marketing as marketing
left join tbl_ccompany as ccompany
on
marketing.db_ccompany=ccompany.db_id

How can i join the tables and have the output i want ?

SELECT db_mid,db_name,GROUP_CONCAT(db_cname) FROM tbl_marketing LEFT JOIN tbl_ccompany on db_id=db_ccompany WHERE db_ccompany in(1,2)

I hope this helps.

Database Structure:

create table tbl_ccompany (
db_id int,
db_cname text );

insert into tbl_ccompany values (1,'xxx');
insert into tbl_ccompany values (2,'yyy');

create table tbl_marketing (
db_mid int ,
db_name text,
db_ccompany text
);

insert into tbl_marketing values (1,'ggg','1,2');

Query:

select db_mid, db_name, group_concat(db_cname) 
from tbl_ccompany tc , tbl_marketing tm
where find_in_set(tc.db_id,tm.db_ccompany)

Reference: http://amitbrothers.blogspot.in/2014/03/mysql-split-comma-separated-list-into.html

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