MySQL SELECT with JOIN - 如何编码正确

时间:2016-11-18 19:54:19

标签: mysql

我有两个表,clientapplication。基本上他们是这样设置的:

我们说表client只有2条记录(行):

ID | company         | street     | city   | country
1    Tea-Export Ltd.   Wallstreet   Mumbai   India
2    Tea-Import Ltd.   Mainstream   London   United Kingdom

application只有一行:

ID | app_num | seller | buyer
1    3002      1        2

对应用程序表的查询将app_num(3002)解析为搜索参数。 并且查询应该只生成一个具有此结构的数组:

$app_data {
  [ID] => [1]
  [app_num] => [3002]
  seller {
    [company] => [Tea-Export Ltd]
    [street] => [Wallstreet]
    [city] => [Mumbai]
    [country] => [India]
  } 
  buyer {
    [company] => [Tea-Import Ltd]
    [street] => [Mainstreet]
    [city] => [London]
    [country] => [United Kingdom]
  } 
}

我知道这可以通过带有JOIN的SELECT语句来实现。 互联网上有很多JOIN例子,但我研究过的都不适合我的例子。因此,建立正确的MySQL语句可以获得任何帮助。

编辑:

来自Jehad Ahmad Jaghoub的解决方案基本上可行,但必须加以填写并完成以从sellerbuyer获取所有地址列:

 (' SELECT 
    s.ID,
    s.app_num,
    a.company AS seller_company ,
    a.street AS seller_street ,
    a.house_num AS seller_house_num ,
    a.postal_code AS seller_postal_code ,
    a.city AS seller_city ,
    a.country AS seller_country ,
    b.company AS buyer_company ,
    b.street AS buyer_street, 
    b.postal_code AS buyer_postal_code ,
    b.city AS buyer_city ,
    b.country AS buyer_country 

  FROM `application`  AS s
  LEFT JOIN clients AS a ON s.seller = a.id  
  LEFT JOIN clients AS b ON s.buyer = b.id  
  WHERE s.app_num = :app_num'); 

$app_data {
  [ID] => [1]
  [app_num] => [3002]
  [seller_company] => [Tea-Export Ltd]
  [seller_street] => [Wallstreet]
  [seller_house_num] => [45a]
  [seller_postal_code] => [400036]
  [seller_city] => [Mumbai]
  [seller_country] => [India]
  [buyer_company] => [Tea-Import Ltd]
  [buyer_street] => [Mainstreet]
  [buyer_house_num] => [345]
  [buyer_postal_code] => []
  [buyer_city] => [London]
  [buyer_country] => [United Kingdom]
}   

但是很多代码都是地狱,因为必须分别选择每一列。在我的情况下它也变得更加复杂,因为country列实际上是另一个ID(country_id),指向一个单独的国家/地区表,其中包含两个针对卖方和买方的JOIN。并且不仅有卖方和买方,还有代理和收货人专栏,我为了简单而离开了。 它也只产生一维数组。那么,是否有更简单的解决方案可用,也可以像上面的例子一样获得多维数组?

2 个答案:

答案 0 :(得分:1)

您需要使用不同的别名两次使用同一个表加入:

SELECT a.ID, a.app_num, seller.*, buyer.*  
FROM Application a 
INNER JOIN Client seller on a.seller = seller.ID
INNER JOIN Client buyer ON a.buyer = buyer.ID
WHERE a.app_num='3002'

看看这是否有效。 seller.*会提供所有卖家详细信息,buyer.*会提供所有买方详细信息。如果您只需要某些列,也可以更改选择字段。

答案 1 :(得分:1)

你可以试试这个吗?我想这就是你想要的。如果没有,请告诉我。

SELECT 
  s.*,
  a.company AS SellerCompany,
  b.company AS BuyerCompany
FROM `application`  AS s
LEFT JOIN client AS a ON s.seller = a.id AND s.id = 1 
LEFT JOIN client AS b ON s.buyer = b.id AND s.id = 1 ;