如何结合这个SQL查询?

时间:2015-01-19 20:45:34

标签: mysql sql magento phpmyadmin

我有这个查询它工作正常,但没有检索确切的信息(名字,姓氏),它只给出第二个名字

SELECT b.email, c.value AS firstname, a.updated_at, d.added_at
    FROM  `wishlist` AS a
    INNER JOIN customer_entity AS b 
ON a.customer_id = b.entity_id
    INNER JOIN customer_entity_varchar AS c 
ON a.customer_id = c.entity_id
    AND c.attribute_id = ( 
    SELECT attribute_id
    FROM eav_attribute
    WHERE attribute_code =  'lastname'
    AND entity_type_id = b.entity_type_id ) 
    INNER JOIN wishlist_item AS d 
ON a.wishlist_id = d.wishlist_id
    INNER JOIN catalog_product_entity AS e 
ON d.product_id = e.entity_id
    LEFT JOIN sales_flat_order AS f ON 
f.customer_email = b.email
    LEFT JOIN sales_flat_order_item AS g 
ON ( f.entity_id = g.order_id
    AND g.sku LIKE CONCAT( e.sku,  '%' ) 
    AND g.product_type =  'simple' ) 
    WHERE d.added_at
    BETWEEN  '2015-01-01'
    AND  '2015-02-01'
    GROUP BY b.email

如果我执行此查询将导致所有客户正确地使用全名

SELECT entity_id, group_concat(VALUE SEPARATOR ' ') AS fullname 
FROM customer_address_entity_varchar AS val
INNER JOIN eav_attribute AS attr 
      ON attr.attribute_id  = val.attribute_id
WHERE attr.attribute_code IN ( 'firstname',  'lastname' ) 

如何编辑检索客户名称的第一个查询部分作为第二个查询的示例? 我有点困惑,我在sql中尝试了很多组合但是没有它们会起作用。

编辑:我更新了第一个长查询,价格不应该在那里。另外我明白该组没有任何意义,但我每个客户只需要1行,所以我将不得不隐藏产品。如果可能的话,同一行中的wishproduct_1,wishproduct2,wishproduct3 ..所有产品都很棒。

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT b.email,
       h.price as firstname,
       c.price AS lastname, 
       a.updated_at, 
       d.added_at
FROM  `wishlist` AS a
INNER JOIN customer_entity AS b 
      ON a.customer_id = b.entity_id
INNER JOIN customer_entity_varchar AS c 
      ON a.customer_id = c.entity_id
      AND c.attribute_id = 
      ( 
          SELECT attribute_id
          FROM eav_attribute
          WHERE attribute_code =  'lastname'
          AND entity_type_id = b.entity_type_id 
       ) 
 INNER JOIN customer_entity_varchar AS h 
      ON a.customer_id = c.entity_id
      AND c.attribute_id = 
      ( 
          SELECT attribute_id
          FROM eav_attribute
          WHERE attribute_code =  'firstname'
          AND entity_type_id = b.entity_type_id 
       )       
INNER JOIN wishlist_item AS d 
      ON a.wishlist_id = d.wishlist_id
INNER JOIN catalog_product_entity AS e 
      ON d.product_id = e.entity_id
LEFT JOIN sales_flat_order AS f 
     ON f.customer_email = b.email
LEFT JOIN sales_flat_order_item AS g 
     ON ( f.entity_id = g.order_id
     AND g.sku LIKE CONCAT( e.sku,  '%' ) 
     AND g.product_type =  'simple' ) 
WHERE d.added_at
    BETWEEN  '2015-01-01' AND  '2015-02-01'
GROUP BY b.email, h.price,  c.price,  a.updated_at,  d.added_at
LIMIT 0 , 30

我假设包含实际名字的字段与包含姓氏的字段相同(尽管价格似乎是一个奇怪的选择)。此外,由于我使用了正确的分组,您可能会注意到您将获得更多记录。在这种情况下,需要将组中的一个或多个字段更改为诸如Max()或Min()的聚合函数,以便每个电子邮件具有一个记录。您的业​​务规则需要指定您将应用的聚合函数。