2
2
2slide2014-03-03 18:08:12
MySQL
2slide, 2014-03-03 18:08:12

How to make the correct sql-query (sql selection - number of records)?

How to change a request?
You need to display all records from the table + and how many links in another table
advert.sity = sity.sity_in
Domodedovo
(3)
Moscow (2)
Kiev (0)

sity
sity_ru              sity_in
--------------------------------
Домодедово     domodedovo
Москва              moskow
Киев                  kiev

adver 
--------------------------------
id         sity
1         domodedovo
2        moskow

Request
SELECT `sity`.`sity_ru`, COUNT(advert.sity) as num 
FROM sity INNER JOIN advert ON advert.sity = sity.sity_in 
GROUP BY sity

Displays only if there is at least a match in the advert table.
If there is no match, then 0 is not output.
Array
(
    [0] => stdClass Object
        (
            [sity_ru] => Домодедово
            [num] => 3
        )

    [1] => stdClass Object
        (
            [sity_ru] => Москва
            [num] => 2
        )

)

Thanks

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stepan, 2014-03-03
@L3n1n

Examples of different join
JOIN and INNER JOIN - in MySQL are completely identical - will return rows when there is at least one match in both tables.
LEFT JOIN - will return rows from the left table, even if there are none in the right one. Those. it always returns rows from the table on the left.
RIGHT JOIN - completely similar to LEFT JOIN, only it will return data from the right table, regardless of whether they have a connection with the left one.
FULL JOIN will return records with at least one match in any of the tables. Actually, this is a combination of LEFT JOIN and RIGHT JOIN

V
victimofbrainlessness, 2014-03-03
@victimofbrainlessness

city!

select s.sity_ru, ifnull(a.count, 0) from city as s left join
(select advert.sity, count (advert.sity) as count from advert group by sity ) as a
on s.sity_in = a.sity

R
Rsa97, 2014-03-03
@Rsa97

SELECT `s`.`sity_ru`, IF (`c`.`count` IS NULL, 0, `c`.`count`) AS `num`
  FROM `sity` AS `s`
    LEFT JOIN (
      SELECT `sity`, COUNT(`sity`) AS `count`
        FROM `adver`
        GROUP BY `sity`
    ) AS `c` ON `c`.`sity` = `s`.`sity_in`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question