简体   繁体   English

使用联接和匹配进行MySQL搜索

[英]MySQL search with joins and match

I've got one table filled with information about companies (tblforetag) in Sweden, one table with provinces (tbllan) and one table with cities (tblstad). 我有一张桌子,上面有关于瑞典公司的信息(tblforetag),一张是省份(tbllan)的表,还有一张城市(tblstad)的表。 The cities are linked to the provinces with id numbers and the company table has a column for the city name (varchar). 这些城市使用ID号链接到各省,并且公司表中有一列用于城市名称(varchar)。

How do I search for all the companies in one province? 如何搜索一个省的所有公司?

I have fiddled around with joins but not got it to work. 我摆弄了join,但没有使它起作用。 I've got this code right now that works but it will only search for company names and cities (in the company table): 我现在有了此代码,该代码可以工作,但它只会搜索公司名称和城市(在company表中):

$sql = "
    SELECT *, 
    MATCH(tblforetag.foretag) AGAINST(:keywords) AS kr
    FROM tblforetag
    WHERE MATCH(tblforetag.foretag) AGAINST(:keywords)
    ";
$sql .= $locisset ? "AND tblforetag.stad LIKE :location" : "";
$sql .= " LIMIT $offset, $rpp"; 
$query = $conn->Prepare($sql);
$query->BindValue(':keywords', $keywords);
if($locisset) $query->BindValue(':location', "%$location%");
$query->Execute();

I do not know your table structure but something along these lines shoulod do the trick: 我不知道您的表格结构,但是按照以下方式应该可以解决问题:

SELECT FROM companies 
LEFT JOIN cities ON (companies.city_id = cities.id)
LEFT JOIN regions ON (cities.region_id = regions.id)
WHERE region.name = 'your region'

This would give you the companies in that particular region. 这将为您提供该特定区域的公司。

I think it would be better the city_name column in companies table to city_id. 我认为将公司表中的city_name列设置为city_id会更好。

SELECT a.*, p.provincename
FROM   companies a, cities c, provinces p
WHERE a.city_name = c.city_name
AND      c.city_id = p.city_id
AND      p.province_id = 5 // give your province id here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM