简体   繁体   English

从另一个表中选择计数更改值

[英]select count change value from another table

i want to ask 我想问问

i have 2 table : 我有2张桌子:

  1. table product (no, product_name, price, city) 表产品(编号,产品名称,价格,城市)
  2. table city (no_city, city_name) 表格城市(no_city,city_name)

in table product field "city" show data "no_city" 在表格产品字段“城市”中显示数据“ no_city”

i mean like this in table product : 我的意思是在餐桌产品中这样:

no | product_name | price | city
1  | apple        | $5    | 1

and in table city like this : 在这样的餐桌城市:

no_city | city_name
1       | london

i have a code for chartjs 我有一个chart.js代码

i use count data from database, this my code 我使用数据库中的计数数据,这是我的代码

$city = $GLOBALS['conn']->GetAll("SELECT city AS `labels`, COUNT(city) AS `values` FROM product GROUP BY city");

in chart preview data city show "1" it should be the city "london" 在图表预览数据城市显示“ 1”中应为城市“伦敦”

the problem is how to change number "1" in chart preview to city name "london" 问题是如何将图表预览中的数字“ 1”更改为城市名称“ london”

i try to use INNER JOIN but not effectiv 我尝试使用INNER JOIN但不起作用

please help me sir 先生,请帮我

how to change number "1" in chart preview to city name "london" 如何将图表预览中的数字“ 1”更改为城市名称“ london”

thank you 谢谢

Use an join to bring in the city names from the other table: 使用联接从另一个表中引入城市名称:

SELECT
    c.city_name AS labels,
    COUNT(p.city) AS values
FROM city c
LEFT JOIN product p
    ON p.city = c.no_city
GROUP BY
    c.no_city, c.city_name

Note that it makes logical sense to left join the city to product table, because that guarantees that every city would appear in your result set. 请注意,将city加入product表是合乎逻辑的,因为这保证了每个城市都会出现在您的结果集中。 For those cities having no products, a count of zero would be reported. 对于那些没有产品的城市,将报告为零。

You can use LEFT JOIN to handle the cases where there are cities with no products. 您可以使用LEFT JOIN来处理没有产品的城市的情况。

try this code : 试试这个代码:

$city = $GLOBALS['conn']->GetAll(
  "SELECT
     city.city_name AS `labels`,
     COUNT(product.city) AS `values`,
     city.no_city
   FROM city c
   LEFT JOIN product p
     ON p.city = c.no_city
   GROUP BY c.no_city"
);

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

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