我有一个包含两列和很多行的表
| id | type |
|----------------|
| 1 | sweater |
| 2 | jeans |
| 3 | pants |
| 4 | trousers |
| 5 | T-shirt |
| 6 | socks |
| 7 | polo |
| 8 | shirt |
| 9 | sweater |
| 10 | jeans |
| 11 | T-shirt |
..................
and so oooon.......
我需要从表中选择8个不同的行,其中包括:帽子,围巾,耳环,项链,戒指,钱包,手套和腰带
我从未需要这样的查询,我曾试图想出smth。
SELECT src,
type
FROM accs_w
WHERE TYPE = 'hat'
OR TYPE = 'earnings'
OR TYPE = 'purse'
OR TYPE = 'scarf'
OR TYPE = 'necklace'
OR TYPE = 'ring'
OR TYPE = 'belt'
OR TYPE = 'gloves'
LIMIT 8
但是,当然它没有给我任何回报
感谢您的回答,谢谢!
答案 0 :(得分:5)
尝试使用IN()
条款:
SELECT src, type FROM accs_w WHERE TYPE IN (
'hat', 'earnings', 'purse', 'scarf', 'necklace', 'ring', 'belt', 'gloves'
)
您不需要LIMIT
输出,因为您知道您将只获得8行(在此特定情况下)。
编辑:
OP似乎需要为其子集中定义的每个SRC
获取一个随机TYPE
。这是如何做到的。
select a.type, (
select b.src
from accs_w b
where b.type = a.type
order by rand()
limit 1
)
from (
select 'T-shirt' as type union all
select 'jeans' as type union all
select 'pants' as type
) as a;
它不漂亮而且 - 我认为 - 不是表演,但它完成了工作。
答案 1 :(得分:0)
这是一个查询,为每种类型随机提供一行。它假设id值的范围是<百万。如果没有,请将1000000增加到更大的值。
create table accs_w
(
id integer,
type varchar(20)
);
insert into accs_w values (1,'sweater');
insert into accs_w values (2,'jeans');
insert into accs_w values (3,'pants');
insert into accs_w values (4,'sweater');
insert into accs_w values (5,'jeans');
insert into accs_w values (6,'pants');
select * from accs_w a
where id in
(
select x mod 1000000 from
( select type, max( floor(rand()*1000000) *1000000 + id) x from accs_w
group by type
) b
);
我假设你想要对每种类型的一行进行采样,只要你得到每种类型的一行,你就不在乎你得到哪一行。