广告表
Screenshot http://img90.imageshack.us/img90/6295/adsvo.png
手机表
Screenshot http://img194.imageshack.us/img194/3713/phones.png
汽车表
Screenshot http://img35.imageshack.us/img35/1035/carsm.png
我想连接表是基于广告表中的类别。
我试过这个问题,但没有运气,有什么帮助吗?
SELECT *
FROM `ads`
JOIN `ads.category` ON `ads.id` = `ads.category.id`
**我无法在你的帖子中添加任何评论,但我想根据广告表中的类别自动添加评论。
例如: - 如果在表中有手机类别,我会自动加入手机表然后
SELECT *
FROM `ads`
JOIN `phone` ON `ads.id` = `phone.id`
如果在表中有汽车类别,我会自动加入汽车表
SELECT *
FROM `ads`
JOIN `cars` ON `ads.id` = `cars.id`
答案 0 :(得分:3)
获得汽车:
SELECT *
FROM ads JOIN cars ON ads.ID = cars.ID
拿到电话:
SELECT *
FROM ads JOIN phones ON ads.ID = phones.ID
两者都使用UNION:
SELECT ads.ID, ads.Title, ads.Desc, ads.category, 'Car' AS AdType, cars.Year AS Col1, cars.cc AS Col2, cars.transmission AS Col3
FROM ads JOIN cars ON ads.ID = cars.ID
UNION ALL SELECT ads.ID, ads.Title, ads.Desc, ads.category, 'Phone' AS AdType, phone.Model AS Col1, phone.Color AS Col2, '' AS Col3
FROM ads JOIN phones ON ads.ID = phones.ID
注意:我建议您在汽车和电话表中设置外键,以引用ads.ID而不是使用子表的ID字段(主键?)
答案 1 :(得分:1)
SELECT ads.*,
cars.year, cars.cc, cars.transmission,
phones.model, phones.color
FROM ads
LEFT JOIN cars
ON cars.id = ads.id
LEFT JOIN phones
ON phones.id = ads.id
虽然我同意@Scrum,但你可以加入它们,然后(在你的代码中)使用type字段并检索正确的列。
我也觉得这些列应该是NULLABLE并且都在一个表中。我没有看到用1-1关系(和直接关键关系)打破这些关键点。这当然不是规范化(我可以看到)。 也许我累了,无能