简体   繁体   English

MySQL选择*与计数

[英]mysql select * with count

I have this query 我有这个查询

SELECT *, COUNT(*) as count FROM PricePaid WHERE Postcode LIKE 'L23 0TP%' GROUP BY Postcode

I am getting this result : 我得到这个结果:

L23 0PT   House number 1    Bella Grove     LIVERPOOL   2 

But what I am looking for is a way to get this result : 但是我正在寻找一种获得此结果的方法:

L23 0PT   House number 1    Bella Grove     LIVERPOOL   2
L23 0PT   House number 17   Bella Grove     LIVERPOOL   2  

You see I am displaying the results on a google map So initially I want to display a marker on the map showing each post code with the number of houses sold on the post code ( the count(*)part ) 您看到我在google地图上显示结果,因此最初我想在地图上显示一个标记,该标记显示每个邮政编码以及该邮政编码上出售的房屋数量(count(*)部分)

And then I need display a list of the propeties from that street in the same query to pass to an info window to then display all the properties on that post code. 然后,我需要在同一查询中显示该街道的属性列表,以传递到信息窗口,然后显示该邮政编码上的所有属性。

Any one any idea if I can do this on one query, any pointers would be greatly appreciated thanks 任何人任何想法如果我可以在一个查询上执行此操作,任何指针将不胜感激,谢谢

You are misusing a nonstandard MySQL extension to GROUP BY . 您正在滥用对GROUP BY的非标准MySQL扩展。 See this: http://dev.mysql.com/doc/refman/5.6/en/group-by-extensions.html 看到这个: http : //dev.mysql.com/doc/refman/5.6/en/group-by-extensions.html

You have two things going on in this query. 您在此查询中有两件事。 One is to provide some details from your table. 一种是从表中提供一些细节。 The other is to present an aggregate. 另一个是提出一个汇总。 You can't do both without using a subquery. 如果不使用子查询,您将无法做到这两者。

Here is what you need: 这是您需要的:

SELECT pp.*, cpp.count
  FROM PricePaid AS pp
  JOIN (
         SELECT Postcode, COUNT(*) AS count
           FROM PricePaid 
          GROUP BY PostCode
       ) AS cpp ON pp.Postcode = cpp.Postcode
 WHERE pp.Postcode LIKE 'L23 0TP%' 

Do you see the virtual summary (aggregate) table JOINed to your physical table? 您是否看到已加入物理表的虚拟摘要(汇总)表? It does the count of properties by postcode. 它按邮政编码对属性进行计数。

         SELECT Postcode, COUNT(*) AS count
           FROM PricePaid 
          GROUP BY PostCode

The JOIN picks up the count for all the properties in the Postcode and includes it in the result set rows with the detail items. JOIN获取邮政编码中所有属性的计数,并将其包括在带有明细项的结果集行中。

The problem (I'm guessing without being able to see your schema) is that you are grouping by the postcode. 问题(我猜是无法看到您的架构)是您按邮政编码分组。 Your desired results each have the same postal code, so they are shown in one row. 每个您想要的结果都具有相同的邮政编码,因此它们显示在一行中。 If you want to have each row and get each row with a count of all of the items, then you should remove your group by statement. 如果您希望每一行都包含所有项目的计数,那么您应该删除group by语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM