2017-06-22 80 views
2

查询1:我现在所面临的问题在左侧加入

SELECT b.id, 
b.bid, 
b.productname, 
b.brandname, 
b.producttype, b.sku, 
b.cat_id, 
b.brandname, 
b.costprice, 
b.pweight, 
b.monthly, 
b.discountcodes, 
b.seller_id FROM `buyde_product` b 
where b.sku in (SELECT buyde_new_new_sku.sku FROM buyde_new_new INNER JOIN buyde_new_new_sku ON buyde_new_new.cat_id = buyde_new_new_sku.cat_id) 

起初,我在上面查询作为那个时候写的,我需要上述资料仅 现在我想从buyde_brand表中添加一个细节,所以我想使用Left Join并使用下面的查询,但在PHPMyAdmin中尝试时会出现错误。

任何人都可以看到我的代码,我错了吗?

SELECT b.id, 
    b.bid, 
    b.productname, 
    b.producttype, b.sku, 
    b.cat_id, 
    b.brandname, 
    b.costprice, 
    b.pweight, 
    b.monthly, 
    ba.brandname, 
    ba.bid, 
    b.discountcodes, 
    b.seller_id FROM `buyde_product` b 
    where b.sku in (SELECT buyde_new_new_sku.sku FROM buyde_new_new INNER 
JOIN buyde_new_new_sku ON buyde_new_new.cat_id = buyde_new_new_sku.cat_id) 

LEFT JOIN `buyde_brand` ba 
ON b.bid = ba.bid 

ERROR:在phpMyAdmin

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'LEFT JOIN buyde_brand ba ON b.bid = ba.bid LIMIT 0, 25' at line 16`

更新:SELECT b.id, b.bid, b.productname, b.producttype, b.sku, b.cat_id, b.brandname, b.costprice, b.pweight, b.monthly, ba.brandname, ba.bid, b.discountcodes, b.seller_id FROM buyde_product b LEFT JOIN buyde_brand ba ON b.bid = ba.bid

如果我上述查询运行通过去除

where b.sku in (SELECT buyde_new_new_sku.sku FROM buyde_new_new INNER JOIN buyde_new_new_sku ON buyde_new_new.cat_id = buyde_new_new_sku.cat_id)

是一部分,那么它运行,但我需要首先获取按这个条件,然后想从buyde_brand

+0

你的加入应该在你的过滤器之前。将连接移到'where b.sku'之前。 – Rob

+0

在'FROM buyde_product b' –

+0

@Rob和Sebastain Bosch之后设置你的左连接,谢谢你,我明白了。 – inrsaurabh

回答

0

添加出价,然后设置你的LEFT JOIN查询的条件(WHERE)之后。您必须在查询的表格部分设置LEFT JOIN。请参阅以下内容:

SELECT 
    b.id, 
    b.bid, 
    b.productname, 
    b.producttype, b.sku, 
    b.cat_id, 
    b.brandname, 
    b.costprice, 
    b.pweight, 
    b.monthly, 
    ba.brandname, 
    ba.bid, 
    b.discountcodes, 
    b.seller_id 
FROM `buyde_product` b LEFT JOIN `buyde_brand` ba ON b.bid = ba.bid 
WHERE b.sku IN (
    SELECT buyde_new_new_sku.sku 
    FROM buyde_new_new INNER JOIN buyde_new_new_sku ON buyde_new_new.cat_id = buyde_new_new_sku.cat_id 
) 

此查询还应该适合你的新的要求,首先筛选buyde_product表,然后LEFT JOIN这个过滤表。结果应该与此解决方案相同。另一种解决方法是将您的原始查询放入子选择中,并在此子选择上选择LEFT JOIN

1

您的SQL语法错误;正确的订单是SELECT-FROM-JOIN-WHERE( - GROUP BY-ORDER BY)。 在你的查询中,你在WHERE子句后面加LEFT JOIN,这是不正确的。 你应该这样写:

SELECT b.id, 
    b.bid, 
    b.productname, 
    b.producttype, b.sku, 
    b.cat_id, 
    b.brandname, 
    b.costprice, 
    b.pweight, 
    b.monthly, 
    ba.brandname, 
    ba.bid, 
    b.discountcodes, 
    b.seller_id 
FROM `buyde_product` b 
LEFT JOIN `buyde_brand` ba 
ON b.bid = ba.bid 
    where b.sku in (SELECT buyde_new_new_sku.sku FROM buyde_new_new INNER 
JOIN buyde_new_new_sku ON buyde_new_new.cat_id = buyde_new_new_sku.cat_id) 
+0

谢谢@ b00n帮助我正确订购 – inrsaurabh