sql - How can I get data for one field from multiple tables? -
i have column contentid
in table identifies content exists in other tables. example, refer pageid
, productid
, etc. plan use pull through other information need, such page name or product name. have far:
select tl.id, tl.tablename, tl.filename, tl.contentid, p.pagename content translationlog tl left join pages p on tl.contentid = p.pageid left join categories c on tl.contentid = c.categoryid left join productdescriptions pd on tl.contentid = pd.sku
the idea each row, want data specified content using tablename
, contentid
fields. currently, i'm able pagename
selecting p.pagename content
. however, i'd each of tables; if row corresponds pages table, query table - same categories , product descriptions. need have alias "content", regardless of field table we're using, such pagename
or productname
.
is possible this?
edit:
the solution posted rd_nielsen perfect, turned out there bit of overlap contentid
. here's ended fix it:
select tl.id, tl.tablename, tl.filename, tl.contentid, coalesce(p.pagename, c.categoryname, pd.productname) translationlog tl left join pages p on tl.contentid = p.pageid , tl.tablename = 'pages' left join categories c on tl.contentid = c.categoryid , tl.tablename = 'categories' left join productdescriptions pd on tl.contentid = pd.sku , tl.tablename = 'products'
if values of translationlog.contentid
can appear in 1 of related tables, can coalesce values tables:
select tl.id, tl.tablename, tl.filename, tl.contentid, coalesce(p.pagename, c.categoryname, pd.productname) content ...
Comments
Post a Comment