简体   繁体   中英

Select multiple fields from columns with distinct and limit

This is my original code and i get only results for the title.

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

I want get results and from another columns and fields like

$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");

I'm guessing you're trying to select a single column from 3 different tables at the same time. If that is the case, you want to use a 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"

It's important to note, you won't be able to tell which rows came from which tables. You'll need to add a controlling column to identify, like so:

"(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"

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