I have this mysql query which in fact someone on Stackoverflow gave me. (It selects the two most frequent id's found together in the columns pic1,pic2 and pic3).
It works great but now I want to add a WHERE clause to the query so that only rows in my table where a particular ID is present are selected. ie.
WHERE pic1 =$loggedin_user OR pic2 = $loggedin_user OR pic3= $loggedin_user
Can anyone tell me where the clause would go within the query below?
The Query
SELECT LEAST(p1, p2) AS p1, GREATEST(p1,p2) AS p2
FROM (
SELECT pic1 AS p1, pic2 AS p2
FROM mytable WHERE pic1 IS NOT NULL AND pic2 IS NOT NULL
UNION ALL
SELECT pic1 AS p1, pic3 AS p2
FROM mytable WHERE pic1 IS NOT NULL AND pic3 IS NOT NULL
UNION ALL
SELECT pic2 AS p1, pic3 AS p2
FROM mytable WHERE pic3 IS NOT NULL AND pic2 IS NOT NULL
) s
GROUP BY LEAST(p1, p2), GREATEST(p1,p2)
ORDER BY COUNT(*) DESC
LIMIT 1