MySQL表别名仅在联盟

时间:2017-02-23 15:53:43

标签: mysql

我有多个表amazonlistings ebaylistings shopifylistings,列SKU列相同。

我尝试创建一个搜索所有这些表中SKU列的查询。现在我用UNION做这个。

$channeldetectquery = "(SELECT SKU as amazon FROM amazonlistings WHERE SKU = '$channelskuarray[$i]') 
    UNION
(SELECT SKU as ebay FROM ebaylistings WHERE SKU = '$channelskuarray[$i]')
    UNION
(SELECT SKU as shopify FROM shopifylistings WHERE SKU = '$channelskuarray[$i]');"

如果我单独做这些......

SELECT SKU as ebay FROM ebaylistings WHERE SKU = 'Product SKU'

它按照预期从ebay提供SKUS ...但由于某些原因,当尝试将上述查询与UNION一起使用时,无论结果如何,它都只提供第一个别名(amazon)。

我的预期结果(现在,我不确定这是否理想,但这是我试图实现的),就像

[amazon]  [ebay]  [shopify]
 SKU 1              SKU 1

[amazon]  [ebay]  [shopify]
           SKU 2 

等...如果找不到SKU则为空结果集(或无结果集),如果找到SKU则为结果。这允许我检查并查看是否在相应的表格中找到了SKU。

1 个答案:

答案 0 :(得分:2)

select union构建一个结果表,一个表只能有一个列名,所以你不能为同一列名分配不同的别名..因此sql只返回第一个

你不能以这种方式从联盟中获得不同的别名

相反,您可以使用适当的值标记每个值

 $channeldetectquery = 
"(SELECT  'amazon' as source, SKU FROM amazonlistings WHERE SKU = '$channelskuarray[$i]') 
    UNION
(SELECT 'ebay', SKU  FROM ebaylistings WHERE SKU = '$channelskuarray[$i]')
    UNION
(SELECT 'shopify', SKU  FROM shopifylistings WHERE SKU = '$channelskuarray[$i]');"

通过这种方式,您可以获得不同的限定行

你可以

select * from 
(SELECT  'amazon' as source, SKU FROM amazonlistings WHERE SKU = '$channelskuarray[$i]') 
    UNION
(SELECT 'ebay', SKU  FROM ebaylistings WHERE SKU = '$channelskuarray[$i]')
    UNION
(SELECT 'shopify', SKU  FROM shopifylistings WHERE SKU = '$channelskuarray[$i]') t
where t.SKU  =  'YOUR_SKU'

获取所有来源的所有YOUR_SKU产品

但如果您需要同一行中相同SKU的所有结果(如您提供的样本中),则应使用左连接

$channeldetectquery = 
"(SELECT amazonlistings.SKU as amazon, ebaylistings.SKU as ebay, hopifylistings.SKU as shopify  FROM amazonlistings 
LEFT JOIN ebaylistings  ON amazon.SKU = ebaylistings.SKU
LEFT JOIN hopifylistings ON amazon.SKU = hopifylistings.SKU
WHERE amazon.SKU = '$channelskuarray[$i]'
WHERE SKU = '$channelskuarray[$i]') ";