0

这是我的数据库结构:# 问题是检索 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

现在我希望所有信息最好通过子查询,例如:

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

我想要查询喜欢(子查询):# 这里是 id 和 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;
4

1 回答 1

2
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')
于 2013-05-31T09:35:24.677 回答