sql从单个表单输入查询多个字段

时间:2011-04-05 15:27:04

标签: php jquery mysql sql

我正在使用php / mysql和jquery ui来自动填充。我需要帮助的是从单个输入(chicago,il)查询db(city,state)中的两个字段。扔我的是如何组合查询中的字段。

有效的示例

SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE City = $foo // 'chicago'
OR Zip = $foo // '01234'
GROUP BY City, State
ORDER BY State;

我想做什么,但没有工作

SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE City = $foo // 'chicago'
OR
City+', '+State = $foo // 'chicago, il'
OR Zip = $foo // '01234'
GROUP BY City, State
ORDER BY State;

(BTW - 州字段是缩写。)

原因是某些城市名​​称只有3或4个字母,并且包含在其他城市名称中,因此用户可能需要输入逗号和状态才能看到自动建议弹出窗口。

5 个答案:

答案 0 :(得分:1)

我在我的数据库上尝试了 CONCAT_WS 并且运行正常,以下查询应该适合您。

CONCAT_WS的语法是here:第一个参数是用于连接字符串的分隔符,这是其他参数

SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE City = $foo // 'chicago'
OR
CONCAT_WS(', ',City, State) = $foo // 'chicago, il'
OR Zip = $foo // '01234'
GROUP BY City, State
ORDER BY State;

答案 1 :(得分:0)

在运行查询之前拆分输入字符串,以便执行以下操作:

SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE City = 'chicago'
OR Zip = '01234'
GROUP BY City, State
ORDER BY State;

如果他们也指定芝加哥,状态变得无关紧要。

答案 2 :(得分:0)

你可以尝试


SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE City = 'chicago'
OR( City LIKE "chicago,%" AND State LIKE '%illinois')

OR Zip = '01234'
GROUP BY City, State
ORDER BY State;

答案 3 :(得分:0)

我建议在括号中包装字符串连接。您还可以在MySQL中使用类似CONCAT()或CONCAT_WS()的函数。

你的意思是“它不起作用”?该条款打破或......?

答案 4 :(得分:0)

SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM
   (SELECT City, State, Zip, (City +', ' + State) AS CityState
    FROM Zips) as SQ
WHERE City = $foo // 'chicago'
OR
CityState = $foo // 'chicago, il'
OR Zip = $foo // '01234'
GROUP BY City, State
ORDER BY State;