我有一个像这样的表结构:
table users
+-------+--------------+
| Field | Type |
+-------+--------------+
| id | INT |
+-------+--------------+
| name | VARCHAR(255) |
+-------+--------------+
我希望单个查询在按字母顺序排序时应返回最长和最小的NAME以及它们各自的长度。
例如
假设数据是(它是假的)
ABA, BBA, PQR, HITS, QUES, PQRST, ABCDE
我希望查询返回
+-------+---+
| ABA | 3 |
+-------+---+
| ABCDE | 5 |
+-------+---+
我试过了:
(
SELECT minName, LENGTH(minName)
FROM (
SELECT name AS minName
FROM users
WHERE LENGTH(name)=(SELECT MIN(LENGTH(name)) FROM users)
) AS maxUsers
ORDER BY minName ASC
LIMIT 1
)
UNION
(
SELECT minName, LENGTH(minName)
FROM (
SELECT name AS minName
FROM users
WHERE LENGTH(name)=(SELECT MAX(LENGTH(name)) FROM users)
) AS maxUsers
ORDER BY minName ASC
LIMIT 1
)
如何简化此查询?任何人?
答案 0 :(得分:1)
这是一个更简单的查询,它返回 all 具有最小和最大长度的名称:
SELECT u.Name, LENGTH(u.Name) as len
FROM users u JOIN
(SELECT MIN(LENGTH(Name)) as minl, MAX(LENGTH(Name)) as maxl
FROM users u
) uu
ON LENGTH(u.name) IN (uu.minl, uu.maxl);
你想要每个长度中的一个。您可以使用其他聚合来获取此信息:
SELECT MIN(u.Name) as Name, LENGTH(u.Name) as len
FROM users u JOIN
(SELECT MIN(LENGTH(Name)) as minl, MAX(LENGTH(Name)) as maxl
FROM users u
) uu
ON LENGTH(u.name) IN (uu.minl, uu.maxl)
GROUP BY LENGTH(u.Name);
答案 1 :(得分:0)
如果你想使用UNION试试这个
(
SELECT
name,
LENGTH(name)
FROM users
ORDER BY LENGTH(name), name ASC
LIMIT 1
)
UNION
(
SELECT
name,
LENGTH(name)
FROM users
ORDER BY LENGTH(name) DESC, name ASC
LIMIT 1
)
答案 2 :(得分:0)
试试这个:更简单,更容易〜
最短的
SELECT MIN(name), LENGTH(MIN(name)) FROM users WHERE LENGTH(name)=(SELECT MIN(LENGTH(name)) FROM users);
最长的
SELECT MAX(name), LENGTH(MAX(name)) FROM users WHERE LENGTH(name)=(SELECT MAX(LENGTH(name)) FROM users);
答案 3 :(得分:0)
许多解决方案提供了一个由多个子查询组成的解决方案,这给SQL初学者带来了很多困惑。这是一个不太复杂的解决方案-
SELECT * FROM (
SELECT <COL_NAME>,LENGTH(<COL_NAME>) AS Length FROM <TABLE_NAME>
ORDER BY 2,1 LIMIT 1
) as MINIMUM
UNION ALL
SELECT * FROM (
SELECT <COL_NAME>,LENGTH(<COL_NAME>) AS Length FROM <TABLE_NAME>
ORDER BY 2 DESC,1 LIMIT 1
) as MAXIMUM;