在连接上选择不同的记录

时间:2010-01-15 00:13:00

标签: mysql select join distinct

我有两个mysql表 - 一个销售表:

+----------------+------------------------------+------+-----+---------+-------+
| Field          | Type                         | Null | Key | Default | Extra |
+----------------+------------------------------+------+-----+---------+-------+
| StoreId        | bigint(20) unsigned          | NO   | PRI | NULL    |       |
| ItemId         | bigint(20) unsigned          | NO   |     | NULL    |       |
| SaleWeek       | int(10) unsigned             | NO   | PRI | NULL    |       |
+----------------+------------------------------+------+-----+---------+-------+

和项目表:

+--------------------+------------------------------+------+-----+---------+-------+
| Field              | Type                         | Null | Key | Default | Extra |
+--------------------+------------------------------+------+-----+---------+-------+
| ItemId             | bigint(20) unsigned          | NO   | PRI | NULL    |       |
| ItemName           | varchar(100)                 | NO   |     | NULL    |       |
+--------------------+------------------------------+------+-----+---------+-------+

销售表包含每个 ItemID 的多个记录 - 每个 SaleWe​​ek 一个记录。我想通过加入这两个表来选择所有出售的商品:

SELECT items.ItemName, items.ItemId FROM items
JOIN sales ON items.ItemId = sales.ItemId 
WHERE sales.StoreID = ? ORDER BY sales.SaleWeek DESC;

但是,这会根据每个 SaleWe​​ek 的多个条目返回多个 ItemId 值。我是否可以选择仅返回一个 ItemID - 我不想查询最新的 SaleWe​​ek ,因为某些商品可能没有最新的条目 SaleWe​​ek 所以我需要获得最后一次促销。我是否需要指定 DISTINCT 或使用 LEFT OUTER JOIN 或其他内容?

4 个答案:

答案 0 :(得分:18)

DISTINCT应该做你想要的事情:

SELECT DISTINCT items.ItemName, items.ItemId FROM items
JOIN sales ON items.ItemId = sales.ItemId 
WHERE sales.StoreID = ? ORDER BY sales.SaleWeek DESC;

这将只返回不同的items.ItemName, items.ItemId元组。

答案 1 :(得分:8)

你也有关于销售周的评论。并且想要最近一周,您可能想尝试使用GROUP BY

SELECT 
      items.ItemName, 
      items.ItemId,
      max( Sales.SaleWeek ) MostRecentSaleWeek
   FROM 
      items JOIN sales ON items.ItemId = sales.ItemId
   WHERE 
      sales.StoreID = ? 
   GROUP BY
      items.ItemID,
      items.ItemName
   ORDER BY
      MostRecentSaleWeek,   -- ordinal column number 3 via the MAX() call
      items.ItemName

如果您希望基于该列,则可能必须将ORDER BY更改为序数第3列引用。此查询将为您提供每个不同的项目以及它出售的最近一周。

答案 2 :(得分:1)

我们可以使用它:

INSERT INTO `test_table` (`id`, `name`) SELECT DISTINCT 
    a.`employee_id`,b.`first_name` FROM `employee_leave_details`as a INNER JOIN 
    `employee_register` as b ON a.`employee_id` = b.`employee_id`

答案 3 :(得分:0)

    SELECT  u.user_name,u.user_id, u.user_country,u.user_phone_no,ind.Industry_name,inv.id,u.user_email
    FROM invitations inv
    LEFT JOIN users u
    ON inv.sender_id = u.user_id
    LEFT JOIN employee_info ei
    ON inv.sender_id=ei.employee_fb_id   
    LEFT JOIN industries ind
    ON ei.industry_id=ind.id
    WHERE inv.receiver_id='XXX'
    AND inv.invitation_status='0'
    AND inv.invitati

on_status_desc='PENDING'
GROUP BY (user_id)