[英]Query a column containing Comma Separated String
我在使用sql
查詢時遇到問題。 基本上我有這種方法:
public function loadByDirectoryContact($directoryContact,$type='')
{
global $db;
$t = 'directoryprogramme';
$query = 'SELECT c.* FROM `'.$t.'` c ';
$query .= 'WHERE `c`.`presenters` = '.$directoryContact->getId().' ';
$query .= 'OR `c`.`staff` = '.$directoryContact->getId().' ';
if($type!=""){
$query .=" AND c.type='".$type."' ";
}
$query .= QueryBuilder::orderBy('name','asc');
echo $query; die();
$db->query($query,$t);
while($db->next($t))
{
$node = new Programme();
$node->setId($db->get('id',$t));
$node->setName($db->get('name',$t));
$node->setBroadcastTime($db->get('broadcast_time',$t));
$node->setDescription($db->get('description',$t));
$node->setDays($db->get('days',$t));
$node->setSubjects($db->get('subjects', $t));
$node->setStaff($db->get('staff',$t));
$node->setPresenters($db->get('presenters',$t));
$directoryCompany = new DirectoryCompany($db->get('directorycompany_id',$t));
$node->setDirectoryCompany($directoryCompany);
$node->setContributors($directoryContact);
$node->setType($db->get('type',$t));
$this->nodes->add($node);
}
}
它創建如下查詢:
SELECT c.*
FROM `directoryprogramme` c
WHERE `c`.`presenters` = 1234
OR `c`.`staff` = 1234
ORDER BY `name` ASC
問題是presenters列存儲逗號分隔的值,因此實際上看起來像這樣
presenters
1234,7738,5097,5100
因此,對於c.presenters
於此列中未c.presenters
任何第一值的任何query
,都不會返回任何結果。 我想知道是否有一種查詢方式可以檢查整個String
?
您可以使用函數FIND_IN_SET在列表中找到您的值:
SELECT c.*
FROM `directoryprogramme` c
WHERE FIND_IN_SET('1234',`c`.`presenters`) > 0
OR `c`.`staff` = 1234
ORDER BY `name` ASC
備注
如果可以的話,請考慮將表格設計標准化。 這意味着針對主持人ID的單獨表,每個ID一行。
您也可以嘗試:
SELECT c.* FROM `directoryprogramme` c WHERE `c`.`presenters` LIKE '%1234%' OR `c`.`staff` = 1234 ORDER BY `name` ASC
我相信presenters專欄是在varchar。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.