1

我想在 mysql php 中为自动完成编写一个查询。我有两个表

CREATE TABLE IF NOT EXISTS `city` (
`id` int(22) NOT NULL AUTO_INCREMENT,
`city_name` varchar(44) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=64 ;

和表2是

CREATE TABLE IF NOT EXISTS `area` (
`id` int(22) NOT NULL AUTO_INCREMENT,
`city_id` int(44) NOT NULL,
 `area_name` varchar(33) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2561 ; 

当用户输入任何单词时,它将在区域表(area_name)和城市表(city_name)中搜索...我想在一个字段中返回结果。例如,如果您输入“RAK”,它将在区域表中搜索。如果找到它将返回 city_id 和 area_name 否则它将在 city.i 中搜索。我需要获取 cityid 、 areaid 和匹配的文本。这怎么可能?

4

4 回答 4

1

有一个OR子句将导致两个表中的表扫描。使用 aUNION将允许使用索引:

    SELECT 
        city_id,
        id AS area_id,
        area_name AS name,
    FROM 
        area
    WHERE
        area_name LIKE 'searchterm%'
UNION
    SELECT 
        id AS city_id
        NULL AS area_id,
        city_name AS name
    FROM 
        city
    WHERE
        city_name LIKE 'searchterm%'
ORDER BY
    name;
于 2013-03-12T19:41:14.813 回答
0

你可能会从这样的事情开始:

select ifnull( area_name, city_name ) from area
   join city on area.city_id = city.id    
   where area_name = <name> or city_name = <name>;

我需要构建一个小提琴来测试它,但存在将一个结果“故障转移”到另一个结果的概念。

于 2013-03-12T18:42:31.710 回答
0

您可以使用此查询

SELECT
    IF(city_name IS NULL ,area_name , city_name) as `Area`
FROM city AS c
LEFT JOIN area AS a ON a.city_id = c.id
WHERE city_name LIKE 'keyword%' OR area_name LIKE 'keyword%'
于 2013-03-12T18:47:35.580 回答
0
SELECT
  c.id, c.city_name, a.id, a.area_name
FROM
  city AS c
LEFT OUTER JOIN area AS a ON a.city_id = c.id
WHERE c.city_name LIKE 'input%'
  OR a.area_name LIKE 'input%'

a.ida.area_name如果匹配仅在城市名称上,则为 null 。

于 2013-03-12T19:47:22.360 回答