mySQL查询选择/加入不按预期工作

时间:2017-03-31 23:53:12

标签: mysql

让我作为序言,我已经做了很多搜索,看看这个问题是否可以解决,但尚未找到相关的答案,所以我现在就问。我有一个查询(大多数)从两个单独的表中拉出来显示四个位置中每个位置的PC模型总数(这些位置在一个列中,所以我试图通过它们选择它们作为自己的列别名)。该查询提取了所有必需的信息,但并不像我希望的那样。

期望:

model | loc1 | loc2 | loc3 | loc4
5530  | 3    | 2    | 1    | 0
6440  | 10   | 0    | 3    | 20

现实:

model | loc1 | loc2 | loc3 | loc4
5530  | 3    | null | null | null
5530  | null | 2    | null | null
5530  | null | null | 1    | null

等。

这是我的查询,如果可能的话,任何有助于使现实符合预期的帮助都会受到赞赏。

SELECT 
      a.model,
      (select COUNT(a.model)
             WHERE a.location = 'AoC-Reno') AS Reno,
      (select count(a.model)
             where a.location = 'AoC-Fargo') AS Fargo,
      (select count(a.model)
              where a.location = 'EoC') AS EoC,
      (select count(a.model)
              where a.location = 'APoC') as APoC
FROM assets AS a
join models m on m.model = a.model  
WHERE m.type IN ('Desktop','Laptop')
AND a.model = m.model
AND a.status != 'Recycled'
GROUP BY m.model, a.location
ORDER BY m.model

2 个答案:

答案 0 :(得分:2)

使用条件聚合:

app.get('/', function (req, res, next) {
  console.log('I'm trying to log this string');
  // make sure to end the response, to prevent hanging requests.
  next();
});

app.use(express.static(path.join(__dirname, 'public')));

您的查询有多个问题:

  • 您正在使用&#34;子查询&#34;,但没有SELECT a.model, SUM(a.location = 'AoC-Reno') AS Reno, SUM(a.location = 'AoC-Fargo') AS Fargo, SUM(a.location = 'EoC') AS EoC, SUM(a.location = 'APoC') as APoC FROM models m JOIN assets a on m.model = a.model WHERE m.type IN ('Desktop', 'Laptop') and a.status <> 'Recycled' GROUP BY m.model ORDER BY m.model; 条款。
  • 您正在按FROMmodel聚合,但每location只需要一行。
  • model条件都在JOIN子句中,并在ON子句中重复。

答案 1 :(得分:1)

您可以进行条件聚合(计数)

WHERE