简体   繁体   English

MySQL:在不知道该列值的情况下选择1列相同的行?

[英]MySQL: Selecting rows where 1 column is the same without knowing the value of that column?

With the following integer columns: 具有以下整数列:
iid, pid, aid iid,pid,援助

I would end up with something like: 我最终会得到类似:

1,1,1 1,1,1
1,1,2 1,1,2
1,1,3 1,1,3
2,1,1 2,1,1
2,1,2 2,1,2
2,1,4 2,1,4

If I want to select iid where pid is 1 and aid is 1,2,3, what's the best way to get that? 如果我要选择pid为1且aid为1,2,3的iid,那么最好的方法是什么? Doing a 做一个

SELECT iid WHERE pid=1 and (aid=1 OR aid=2 OR aid=3)

returns every row but the last one. 返回除最后一行以外的每一行。

Is there a better table structure to use? 有没有更好的表结构可以使用? pid is a row in another table that can have several values. pid是另一个表中的行,可以有多个值。 This table gives me the iid, a master id for that row with certain values. 该表为我提供了iid,即具有特定值的该行的主ID。 There is no set number of values, though, so it seems like I need a 1 to many table, but trying to get that down to the 1 iid seems inefficient. 但是,没有设置数量的值,因此似乎我需要一个1对多表,但是尝试将其降低到1个iid似乎效率低下。

If you want to use your current table structure, you could do the following to select the iid you want. 如果要使用当前的表结构,则可以执行以下操作以选择所需的iid。

SELECT 
     iid, pid, GROUP_CONCAT(aid) as grp 
FROM 
     test 
WHERE 
     pid = 1 
GROUP BY 
     pid, iid 
HAVING 
     grp = '1,2,3';

+------+------+-------+
| iid  | pid  | grp   |
+------+------+-------+
|    1 |    1 | 1,2,3 |
+------+------+-------+
1 row in set (0.06 sec)

With the group query you can see the AID attributes together grouped by PID and then IID. 通过组查询,您可以看到按PID和IID分组在一起的AID属性。

SELECT iid, pid, GROUP_CONCAT(aid) as grp 
FROM test 
GROUP BY pid, iid;
+------+------+-------+
| iid  | pid  | grp   |
+------+------+-------+
|    1 |    1 | 1,2,3 |
|    2 |    1 | 1,2,4 |
+------+------+-------+
2 rows in set (0.03 sec)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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