Forum Moderators: open
I have this table:
+--------+------+
¦ number ¦ id ¦
+--------+------+
¦ 1 ¦ 10 ¦
¦ 1 ¦ 11 ¦
¦ 1 ¦ 12 ¦
¦ 2 ¦ 50 ¦
¦ 2 ¦ 7 ¦
¦ 2 ¦ 11 ¦
¦ 3 ¦ 11 ¦
+--------+------+
All I need to do is find where the column 'id' occurs in each of the 'number' fields. So, in the above example, the desired result is '11' because the number 11 occurs at least once in number 1, number 2, and number 3.
How do I get there? Thanks!
--------+------+
¦ number ¦ id ¦
+--------+------+
¦ 1 ¦ 10 ¦
¦ 1 ¦ 11 ¦
¦ 1 ¦ 11 ¦ *
¦ 1 ¦ 12 ¦
¦ 2 ¦ 50 ¦
¦ 2 ¦ 7 ¦
¦ 2 ¦ 11 ¦
¦ 3 ¦ 11 ¦
+--------+------+
I am using MySQL, so I had to modify the queries, but yours, aspdaddy, had trouble with the duplicate. Graham, at first glance, yours seems to work, but I hadn't had time to figure out why and don't know if it will work in all instances.
SELECT table1.id
FROM table1
GROUP BY table1.id HAVING COUNT(table1.number)
>= (SELECT COUNT(number) FROM (SELECT DISTINCT(number) FROM table1) AS t2)
Basically the same as aspdaddy's query, except w/ an alias to make MySQL happy and the ">=" to allow for dups. I've yet to test it extensively...thanks.
SELECT id
FROM
( SELECT number, id
FROM table1
GROUP BY number, id) AS t2
GROUP BY ID
HAVING COUNT(*) = (SELECT COUNT (DISTINCT number) FROM table1)