简体   繁体   中英

mysql select distinct n row that has a certain value

Considering here is my table query:

id    name  number   Code
1     red     1       A
2     red     3       B
3     blue    3       C
4     blue    5       A
5     purple  2       D
6     yellow  3       D
7     yellow  4       C

Now I need to query to get 2 random row such that there is 1 name is red and 1 number is 3, kinda like this:

SELECT * FROM table WHERE name = "red" LIMIT 1 and number = 3 LIMIT 1

So like row 1+3,1+6 or 2 + any other row. Here is my query:

SELECT * FROM table
        group by name,number
        having count(name="red") = 1
             and count(number=3) = 1
ORDER BY RAND()
LIMIT 2;

However, it seems like it just query the row randomly and not satisfying my requirement. Can anyone show me what is wrong? Thank you.

If you can live with odd formatting...

select x.id x_id
 , x.name x_name
 , x.number x_number
 , x.code x_code
 , y.id y_id
 , y.name y_name
 , y.number y_number
 , y.code y_code
    
   from my_table x
   join my_table y
     on y.id <> x.id
  where x.name = 'red'
    and y.number = 3
 order by rand()
 limit 1;

https://www.db-fiddle.com/f/6JmLKq1RwaPrSwS3zx4Qmt/0

Previously, I posted this solution, but it too has some flaws, I think. But TB liked it, so I'll keep it here...

select * 
   from my_table where name = 'red'
  union distinct
select * 
   from my_table where number = 3
 order by rand()
 limit 2

I think that this will do what you want:

select t1.*
from tablename t1 
inner join (
  select t1.id id1, t2.id id2
  from tablename t1 inner join tablename t2
  on t2.id > t1.id 
  and ('red' in (t1.name, t2.name)) + ('3' in (t1.number, t2.number)) = 2
  order by rand() limit 1
) t2 on t1.id in (t2.id1, t2.id2)

Note that the row with the highest probability to be returned is id = 2 , because it can be combined with any other row of the table.
See the demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM