简体   繁体   中英

select count change value from another table

i want to ask

i have 2 table :

  1. table product (no, product_name, price, city)
  2. table city (no_city, city_name)

in table product field "city" show data "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

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"

the problem is how to change number "1" in chart preview to city name "london"

i try to use INNER JOIN but not effectiv

please help me sir

how to change number "1" in chart preview to city name "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. 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.

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"
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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