How to JOIN on different tables based on column value
PROBLEM:
ads
table

phones
table
i
have 3 tables ads,cars and phones.
i
want to join tables is based on category in ads table.
and
i tried this query but no luck,any helps?
SELECT*FROM`ads`JOIN`ads.category`ON`ads.id` = `ads.category.id`
**
i cant add comment any of your post,but i want it to be automatic
based on category in ads table.
for
example :- if in table have phones category,i will automatic join
phones table then
SELECT*FROM`ads`JOIN`phone`ON`ads.id` = `phone.id`
if
in table have cars category,i will automatic join cars table
SELECT*FROM`ads`JOIN`cars`ON`ads.id` = `cars.id`
SOLUTION:
to
get the cars:
SELECT*FROMadsJOINcarsONads.ID = cars.ID
to
get the phone:
SELECT*FROMadsJOINphonesONads.ID = phones.ID
to
get both use a UNION:
SELECTads.ID, ads.Title, ads.Desc, ads.category,'Car'ASAdType, cars.YearASCol1, cars.ccASCol2, cars.transmissionASCol3FROMadsJOINcarsONads.ID = cars.IDUNIONALLSELECTads.ID, ads.Title, ads.Desc, ads.category,'Phone'ASAdType, phone.ModelASCol1, phone.ColorASCol2,''ASCol3FROMadsJOINphonesONads.ID = phones.ID
note:
i would advise you to setup foreign keys in your cars and phones
tables, to reference the ads.ID instead of using the ID field
(Primary key?) of the child tables





0 comments:
Post a Comment