简体   繁体   中英

complex mysql query with 3 tables

now i have three tables ok?

  1. catgories | cat_id
  2. areas | area_id
  3. ads | cat_id - area_id

now i want get the the areas under the catgories with contain the ads this mean - catgorty -- area contant catgorty ads example i have cars as a catgory and egypt as area and a car for sale as ads now i want show the areas under the catgories which contain ads this mean i have egypt usa canda and one ads in egypt now i want show it like cars -- egypt and if i have one more ad in the usa it appear cars --egypt --usa this mean give me the areas with contain ads under that catgory

countries with adds:

SELECT *
  FROM areas
 WHERE area_id in (SELECT area_id FROM ads) 

countries with adds for cars:

SELECT *
  FROM areas
 WHERE area_id in (
    SELECT ads.area_id
      FROM ads,categories
     WHERE ads.cat_id = categories.cat_id
       AND categories.cat_name = 'cars') 

is that what you meant?

You are looking for GROUP BY :

SELECT cat_id, group_concat(area_id) from ads group by cat_id;

Assuming *cat_id* is the actual value ( cars ) and not an auto_increment. If so, use INNER JOIN .

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