2014-10-08 75 views
0

加入MySQL的类型我有2个表结构如下动态设置通过PHP

产品

[id] [name]   [setting_id] 
    1  pendrive   6 
    2  laptop    3 
    3  mobile    2 
    4  vallet    7 
    5  clothes    4 

store_product

[id]   [name]   [storeid] 
    2  laptop_store  1 
    3  mobile_mobile  1 
    5  clothes_store  4 
    8  new1_store   2 
    9  new2_store   3 

我想造成这样的

[id] [name] 
    1  pendrive 
    2  laptop_store 
    3  mobile_mobile 
    4  vallet 
    5  clothes_store 
    8  new1_store 
    9  new2_store 

我曾尝试此查询,但只给出了但没有new1_store和new1_store

SELECT products.id , CASE WHEN store_product.name IS NOT NULL AND store_product.name!='' THEN store_product.name ELSE products.name END AS name 
    from products 
    left join store_product on store_product.id = products.id 

当我从左边知道加入它是不可能的,但可以请提出优化的查询(避免工会的左连接和右连接)。如果可能比请回答

感谢

回答

1

在MS-SQL Server中,我会用下面的查询解决此问题:

Select Id, Name from Products P 
Where Not Exists (Select * from Store_Product SP where SP.Id = P.Id) 
Union All 
Select Id, Name from Store_Product 

对于MySQL,我不知道。

+0

很好的答案...但它可能没有工会?.. thnks – 2014-10-08 09:42:19

+0

你不想要一个联盟,你不想要的左,右外连接既不是一个组合。我很抱歉地说,但这是你的设计是错误的。对于各种产品,您应该只有一个表格,并且有适当的字段来区分它们的类型。 – SylvainL 2014-10-08 09:55:37

0

我会做下面的事情。 第一部分选择products表中可能存在的产品的ID和名称,也可能选择store_product表中的产品。 第二部分使用仅存在于store_product表中的ID填充行的ID和名称。

(SELECT products.id, COALESCE(store_product.name, products.name) as name 
FROM products 
LEFT JOIN store_product ON store_product.id = products.id) 

UNION 

(SELECT store_product.id, store_product.name as name 
FROM store_product 
LEFT JOIN products ON store_product.id = products.id 
WHERE products.id IS NULL) 

ORDER BY id 
+0

这是正确的答案...但正如我在问题中指定,我想避免工会...因为我有大桌子,所以联盟给服务器上这么多的负载....如果可能比请建议...无论如何谢谢你快速回答 – 2014-10-08 09:44:49

+0

如果你想避免工会,你必须做另一个JOIN,我相信这会给服务器带来更多负担。尝试查询'EXPLAN(从上面的队列)并发布结果,如果它实际上性能低下,这将是一个很好的提示。 – Kleskowy 2014-10-08 10:00:19