我需要写一个这样的查询:
SELECT * FROM users WHERE user_name='somthing' ELSE WHERE user_name LIKE 'something%' ORDER BY user_name;
但我不确定如何写它。
表格如下:
id | user_name | frequency
第一条记录是
4 | fred | 1
所以当搜索user_name =' fred'如果有完全匹配,则显示最常见的记录(最高频率值)否则如果没有完全匹配则显示结果,例如' fred'
我复制了一个例子。链接是http://www.peachpit.com/articles/article.aspx?p=1802754&seqNum=3
答案 0 :(得分:1)
CREATE TABLE users
(
id INT,
user_name VARCHAR(255),
frequency INT
);
INSERT INTO users
VALUES
(4,'fred',1),
(5,'fred',2),
(6,'frederick',1),
(7,'freddie',1),
(8,'freddie',2),
(9,'john',1);
(
SELECT *
FROM users
WHERE user_name = 'fred'
ORDER BY Frequency DESC
LIMIT 1
)
UNION
(
SELECT *
FROM users
WHERE user_name LIKE '%fred%' AND
NOT EXISTS (
SELECT *
FROM users
WHERE user_name = 'fred'
ORDER BY Frequency
LIMIT 1
)
)