从具有distinct和limit的列中选择多个字段

时间:2014-09-06 00:44:11

标签: php mysql sql

这是我的原始代码,我只获得标题的结果。

$result = $db->fetchRowList("select Distinct `title` from ".TABLE_ADS." where `title` like '$term%' limit 10");

我希望获得结果以及其他列和字段,例如

$result = $db->fetchRowList("select Distinct `title` from ".TABLE_ADS." where `title` like '$term%' and ".TABLE_MESSANGES." where `messange` like '$term%'  and ".TABLE_CARS." where `model` like '$term%' limit 10");

1 个答案:

答案 0 :(得分:0)

我猜你正在尝试同时从3个不同的表中选择一个列。如果是这种情况,您希望使用Union

"(SELECT `title` FROM ".TABLE_ADS." WHERE `title` LIKE '$term%') UNION (SELECT `messange` FROM ".TABLE_MESSANGES." WHERE `messange` LIKE '$term%') UNION (SELECT `model` FROM ".TABLE_CARS." WHERE `model` LIKE '$term%') LIMIT 10"

重要的是要注意,您将无法分辨哪些行来自哪些表。您需要添加一个控制列来识别,如下所示:

"(SELECT `title`, 'ad' as `table` FROM ".TABLE_ADS." WHERE `title` LIKE '$term%') UNION (SELECT `messange`, 'messange' as `table` FROM ".TABLE_MESSANGES." WHERE `messange` LIKE '$term%') UNION (SELECT `model`, 'car' as `table` FROM ".TABLE_CARS." WHERE `model` LIKE '$term%') LIMIT 10"