MySQL - 选择N个不同记录所在的所有行

时间:2021-11-19 07:57:53

I have a table with addresses, dates and some other info.

我有一张包含地址,日期和其他信息的表格。

I want to select an N unique quantity of addresses, and of that N records, I want to select everything from all the rows where that address is, because the address is not a unique value in that column.

我想选择N个唯一数量的地址,并且在N个记录中,我想从该地址的所有行中选择所有内容,因为该地址不是该列中的唯一值。

Date      |     Address       |    MoreInfo
1/2/2000  |   123 SUPER LN    |   SOME MORE BORING INFO
2/3/2000  |   123 SUPER LN    |   SOME MORE BORING INFO
5/3/2000  |   567 AWESOME ST  |   SOME MORE BORING INFO
5/26/2000 |   567 AWESOME ST  |   SOME MORE BORING INFO
7/2/2000  |   987 SUPER LN    |   SOME MORE BORING INFO
8/3/2000  |   1100 BORING DR  |   SOME MORE BORING INFO
11/7/2000 |   1100 BORING DR  |   SOME MORE BORING INFO
1/5/2001  |   564 SUPER LN    |   SOME MORE BORING INFO

So for that data, I would like to get, say 3 different addresses, (123 SUPER LN, 567 AWESOME ST, 987 SUPER LN) and get everything from all the rows those 3 addresses are at.

所以对于那些数据,我想得到3个不同的地址(123 SUPER LN,567 AWESOME ST,987 SUPER LN)并从这3个地址所在的所有行中获取所有内容。

I had a query:

我有一个问题:

SELECT *
FROM my_table
WHERE my_condition = true
GROUP BY address

But this brings only 1 row per address, and I would like to get all the rows where those N addresses are at. Thanks!

但是这每个地址只带一行,我想获得那些N个地址所在的所有行。谢谢!

1 个解决方案

#1


3  

I think this is what you want:

我想这就是你想要的:

select t.*
from (select distinct address
      from my_table
      where my_condition = true
      limit 100  -- this is the N
     ) a join
     my_table t
     on a.address = t.address;

The first subquery gets the list of addresses. The join brings back the original rows.

第一个子查询获取地址列表。连接将返回原始行。

#1


3  

I think this is what you want:

我想这就是你想要的:

select t.*
from (select distinct address
      from my_table
      where my_condition = true
      limit 100  -- this is the N
     ) a join
     my_table t
     on a.address = t.address;

The first subquery gets the list of addresses. The join brings back the original rows.

第一个子查询获取地址列表。连接将返回原始行。