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