简体   繁体   中英

Subquery to join column's in same table?

here this is my database structure : # problem is to retrieval of pref_country

OrderLead :
 id   lead   order  time   #lead is foreign key to leaddeatail
 1    10     34     null
 2    14     34     null
 3    17     37     null

leaddetail :                           # all pref_country foreign key to Country
 id   name  pref_country_1   pref_country_2   pref_country_3 
 4    rosh         3              4                   null
 10   amit         4              2                   3
 14   xxx          2             null                 null

Country :
 id   name 
 2    India 
 3    USA 
 4    UK

now i want all information preferably by sub queries like:

orderleadid   lead_name    lead_pref_country  orderlead_time # where order = 34
1             amit         Uk,India,USA       null
2             xxx          India              null

i want query like(subquery) : # here for id and contry

SELECT id,(SELECT group_concat(P.country separator ",") from Country as P, leaddetail as LD where LD.id = orderlead.lead and LD.pref_contry_1 = P.id ) as pref country from orderlead where order = 34;
SELECT 
  OrderLead.id AS orderleadid,
  leaddetail.name AS lead_name,
  CONCAT(IFNULL(c1.id,''), IF(c2.id IS NULL,'', CONCAT(',',c2.name)), IF(c3.id IS NULL,'', CONCAT(',',c3.name))) AS lead_pref_country,
  OrderLead.time AS orderlead_time
FROM OrderLead
  INNER JOIN leaddetail ON leaddetail.id=OrderLead.lead
  LEFT JOIN Country AS c1 ON c1.id=leaddetail.pref_country_1
  LEFT JOIN Country AS c2 ON c2.id=leaddetail.pref_country_2
  LEFT JOIN Country AS c3 ON c3.id=leaddetail.pref_country_3
-- e.g. WHERE OrderLead.order = 34
-- e.g. WHERE (c1.name='India' OR c2.name='India' OR c3.name='India')

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