mysql - 带连接的条件 - 只有不同的行

时间:2018-01-30 19:23:44

标签: mysql sql

抱歉没有准确的主题。更精确的描述如下: 考虑示例表:

城市:

cityId  | cityName
----------------------
51      | NY
52      | Chicago
53      | SanFrancisco

人:

peopleId | peopleName | 
-----------------------
21        | John      |  
22        | Emma      | 
23        | Frank     | 
24        | George    | 
25        | Albert    | 

商品:

goodsId | good   | peopleId  | cityId
------------------------------------
1       | bread  |  21       |  51
2       | steel  |  22       |  51
3       | onion  |  23       |  0 
4       | chair  |  22       |  52
5       | knife  |  22       |  0

输入数据: cityId:51 peopleId:(21,22,23,25)

预期结果:

peopleId | peopleName | cityId | cityName | goodId | good
-----------------------------------------------------------
   21    | John       |  51    |  NY      |   1    | bread
   22    | Emma       |  51    |  NY      |   2    | steel 
   23    | Frank      |  0     |  ---     |   3    | onion
   25    | Albert     |  ---   |  ---     |  ---   | ----
   22    | Emma       |  0     |  ---     |   5    | knife

即使几乎是空数据,仍会显示某行(此处为peopleId 25)。这是怎么回事?

我想选择所有货物。在输入数据(21,22,23,25)和cityId = 51中有people.peopleId。但是货物表中的每一行都没有指定goods.cityId,也没有每个goods.peopleId都在货物表中。我希望我的结果有条件依赖:

  • 如果peopleId存在于商品表中,而且此行还有cityId我正在查找 - 打印它。
  • 如果peopleId存在于商品表中,但goods.cityId = 0 - 请选择它。
  • 否则如果peopleId不存在于商品表中 - 仅打印peopleId和peopleName,其余字段将留空。

我已经做到了:

SELECT DISTINCT people.peopleId, people.peopleName, 
CASE 
   WHEN goods.cityId = 51
       THEN (SELECT goods.good FROM goods WHERE goods.zalozenie = 51 AND goods.peopleId = people.peopleId)
       ELSE 

CASE 
       WHEN goods.cityId = 0
       THEN (SELECT goods.good FROM goods WHERE goods.cityId = 0 AND goods.peopleId = people.peopleId)
ELSE -1
END 
END AS goods FROM people LEFT JOIN goods ON people.peopleId = goods.peopleId  WHERE people.peopleId IN ( 21, 22, 23, 25 )

这几乎没问题,但结果显示:

peopleId | peopleName | cityId | cityName | goodId | good
-----------------------------------------------------------
   21    | John       |  51    |  NY      |   1    | bread
   22    | Emma       |  51    |  NY      |   2    | steel 
   23    | Frank      |  0     |  ---     |   3    | onion
   25    | Albert     |  ---   |  ---     |  ---   | ----
   22    | Emma       |  0     |  ---     |   5    | knife

不需要的行是最后一行 - 如果peopleId = 22 with cityId>它应该只选择第二行并忽略最后一行0已经结果。 希望你能帮我!

Kalreg

1 个答案:

答案 0 :(得分:0)

我认为你正在尝试做这样的事情:

SELECT p.peopleId, p.peopleName, c.cityId, c.cityName, g.goodId, g.good
FROM people p left join goods g
    on p.peopleId = g.peopleId
  left join city c
    on c.cityId = g.cityId
WHERE  
  (g.goodId is null or g.cityId = 51 or (g.cityId = 0 and NOT EXISTS (SELECT * FROM goods g2 WHERE g2.peopleId=p.peopleId and g2.cityId>0)))
  and p.peopleId IN (21, 22, 23, 25);

请参阅此sql fiddle以稍微讨论一下。无论如何,希望这是一个起点。