CREATE TABLE table1
(`id` int not null auto_increment primary key, `data` char(3),`subject` varchar(250)) ;
INSERT INTO table1
(`id`, `data`,`subject`)
VALUES
(1, 'xa','aad'),
(2, 'ya','aac'),
(3, 'yc','aae'),
(4, 'zb','aaf'),
(5, 'yb','aag'),
(6, 'xc','aah'),
(7, 'za','aai');
如表中所示,如何找到所有 不同的值,这些值以数据列中的第一个字母开头
例如:
select * from table1 where data like '%x%' limit 1;
select * from table1 where data like '%y%' limit 1;
select * from table1 where data like '%z%' limit 1;
进入单个查询并获取此输出,如下所示
输出
1, 'xa', 'aad'
2, 'ya','aac'
3, 'zb','aaf'
答案 0 :(得分:1)
组合DISTINCT
和LEFT
?但是不要忘记这种方法不能使用索引。
SELECT distinct(LEFT(`data`, 1)) first_letter, id, `data`, subject
FROM table1
GROUP BY first_letter
答案 1 :(得分:1)
单一查询
select
id,
data,
LEFT(group_concat(subject order by id),LOCATE(',',group_concat(subject order by id)) - 1),
from table1
group by SUBSTRING(data, 1, 1)
答案 2 :(得分:0)
您可以使用子查询获得每个组的第一个id
SELECT *
FROM table1
WHERE id IN (
select min(id) from table1
where data like '%x%'
OR data like '%y%'
OR data like '%z%'
GROUP BY left(data, 1)
)
答案 3 :(得分:-1)
使用UNION
:
(select * from table1 where data like '%x%' limit 1)
UNION ALL
(select * from table1 where data like '%y%' limit 1)
UNION ALL
(select * from table1 where data like '%z%' limit 1) ;
请注意:您必须将每个查询括在()
中以限制每个查询的工作,否则您将只获得一行而不是三行。
另请注意,'%z%'
会在任何位置为您提供包含z
的值,而不仅仅是第一个字符。您需要使用LEFT(data, 1) = 'z'
代替:
(select * from table1 where LEFT(data, 1) = 'x' limit 1 )
UNION ALL
(select * from table1 where LEFT(data, 1) = 'y' limit 1)
UNION ALL
(select * from table1 where LEFT(data, 1) = 'z' limit 1 )