I have a table that looks like so:
+-----+--------------+---------+----------+---------------------+---------------------+ | id | username | case_id | status | date_assigned | date_removed | +-----+--------------+---------+----------+---------------------+---------------------+ | 21 | hemcreynolds | 802 | inactive | 2007-08-20 07:15:48 | 2008-04-15 16:08:54 | | 133 | licox | 868 | active | 2007-09-02 11:55:37 | 0000-00-00 00:00:00 | | 3 | kashepherd | 794 | inactive | 2007-08-17 13:54:39 | 2010-08-12 14:40:37 | | 4 | tithomas | 795 | active | 2007-08-17 13:56:06 | 0000-00-00 00:00:00 | | 5 | stcosse | 795 | inactive | 2007-08-17 13:56:26 | 2007-09-25 10:02:03 | | 6 | mefong yit | 914 | active | 2007-08-17 14:00:29 | 0000-00-00 00:00:00 | | 7 | tamouledoux | 842 | active | 2007-08-17 14:09:16 | 0000-00-00 00:00:00 | | 9 | chgross | 903 | active | 2007-08-18 08:38:38 | 0000-00-00 00:00:00 | | 20 | ticrane | 802 | inactive | 2007-08-20 07:15:41 | 2008-04-15 16:44:35 | | 19 | hemcreynolds | 818 | inactive | 2007-08-20 07:15:12 | 2008-04-15 16:08:57 | +-----+--------------+---------+----------+---------------------+---------------------+
I’d like to run a query to find which cases a user has been assigned to by username, e.g.
SELECT username,case_id from assignments WHERE username = 'ticrane'
I would then like to find all the other users assigned to the cases that my user (ticrane) is assigned to:
SELECT * FROM assignements WHERE case_id = (all of the case ids generated by the previous query)
I’d like to do this in a single query. I imagine that some kind of join is in order here, but I don’t think you can join results from the same table. Confused. Any suggestions?
It is perfectly legal to join a table to itself, but you need to give an alias to at least one of the two “copies” of the table so that the statement is not ambiguous.