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');
鲜明通配符:如何找到在如表中如何可以找到所有的<strong><em>不同的值,其在数据列</em></strong></p> <p>的第一个字母为如开头所示声明的MySQL
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'
组合DISTINCT
和LEFT
?但不要忘记,这种方法并不使用索引。
SELECT distinct(LEFT(`data`, 1)) first_letter, id, `data`, subject
FROM table1
GROUP BY first_letter
如果only_full_group_by没有设置。 –
区别不是一个函数,它不会与group by子句一起使用。 – Strawberry
使用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)
使其成为单一的查询
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)
您可以使用子查询来获得第一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)
)
难道你不能只做极限1的那些查询吗?多数民众赞成在我怎么明白你想要什么.. – Zulatin
@ Zulatin,但在输出 – dude
'UNION'显示在一个查询?另外,如果你只想要那些以x,y和z开头的,你想删除前导通配符,所以:'LIKE'x%''... – kchason