开发者

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

开发者 https://www.devze.com 2023-02-17 03:28 出处:网络
With the following integer columns: iid, pid, aid I would end up with something like: 1,1,1 1,1,2 1,1,3 2,1,1

With the following integer columns:

iid, pid, aid

I would end up with something like:

1,1,1

1,1,2

1,1,3

2,1,1

2,1,2

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? 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. This table gives me the iid, a master id for that row with certain values. 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.


If you want to use your current table structure, you could do the following to select the iid you want.

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.

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消