MySQL:如何从另一个表中的列中选择数据

时间:2013-10-13 01:48:17

标签: mysql

我有以下select语句:

  SELECT
    items.id,
    items.name AS item_name,
    items.tobuy,
    items.list_id,
    items.note,
    items.unit,
    MIN(NULLIF(packages.ppu, 0)) AS mppu,
    packages.price AS mprice,
    items._deleted
  FROM
    items
  INNER JOIN
    lists ON lists.id = items.list_id
  LEFT JOIN
    packages ON items.id = packages.item_id
  WHERE
    lists.user_id = 1 AND
    items._deleted = '0'
  GROUP BY
    items.id
  ORDER BY
    tobuy DESC,
    item_name

但我真正想要的是具有最小ppu的包装的价格(不一定是具有最低价格的包装)。

有什么想法吗?

样本记录:

表:项目:

id,  name,  tobuy, list_id, note, unit, _deleted
95,  test1, 1,     1,       null, null, 0
69,  test2, 1,     1,       null, null, 0
194, test3, 1,     1,       null, null, 0
162, test4, 1,     1,       null, null, 0

表:列表:

id, name,  user_id
1,  list1, 1

表:包:

id,  item_id, price, ppu
392, 95,      0,     0
117, 95,      13.49, 0.078
391, 95,      0,     0
386, 69,      0,     0
387, 69,      0,     0
388, 69,      0,     0
368, 194,     4.58,  0.138
18,  194,     3.38,  0.177
17,  194,     3.88,  0.144

结果应该是四个项目,并提供以下信息:

id,  item_name,  tobuy, list_id, note, unit, mppu,  mprice, _deleted
95,  test1,      1,     1,       null, null, 0.078, 13.49,  0
69,  test2,      1,     1,       null, null, 0,     0,      0
194, test3,      1,     1,       null, null, 0.138, 4.58,   0
162, test4,      1,     1,       null, null, 0,     0,      0

请注意,项目162没有任何相应的包,但它仍然显示在列表中。这就是“LEFT JOIN”的原因

BTW,“mppu”代表“每单位最低价格”

3 个答案:

答案 0 :(得分:0)

你可以尝试第二个左边:     packages ON ( packages.item_id = items.id and select min(packages.ppu) from packages where item_id=item.id)

还要确保将group by更改为items.id 未经测试

答案 1 :(得分:0)

使用mysql,这非常简单。

按ppn排序并将组移至外部查询

SELECT * FROM (
  SELECT
    items.id,
    items.name AS item_name,
    items.tobuy,
    items.list_id,
    items.note,
    items.unit,
    MIN(NULLIF(packages.ppu, 0)) AS mppu,
    packages.price AS mprice,
    items._deleted
  FROM items
  INNER JOIN lists
    ON lists.id = items.list_id
    AND lists.user_id = 1
  LEFT JOIN packages
    ON items.id = packages.item_id
  WHERE items._deleted = '0'
  ORDER BY
    ppm,
    tobuy DESC,
    item_name) x
GROUP BY
  id

答案 2 :(得分:0)

以下工作可以获得我正在寻找的结果。

SELECT * FROM (  
  SELECT
    items.id,
    items.name AS item_name,
    items.tobuy,
    items.list_id,
    items.note,
    items.unit,
    NULLIF(packages.ppu, 0) AS mppu,
    packages.price AS mprice,
    items._deleted
  FROM
    items
  INNER JOIN
    lists ON lists.id = items.list_id
    AND lists.user_id = 1 
  LEFT JOIN
    packages ON packages.item_id = items.id
  WHERE
    items._deleted = '0'
  ORDER BY
    tobuy DESC,
    item_name,
    IFNULL(mppu, 999999)) x
GROUP BY
  x.id
ORDER BY
  tobuy DESC,
  item_name

感谢大家的参与,让我了解了这一点。