我有一张看起来像这样的表:
+-----+--------------+---------+----------+---------------------+---------------------+ | 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 | +-----+--------------+---------+----------+---------------------+---------------------+
我想运行查询以查找用户已按用户名分配的情况,例如
SELECT username,case_id from assignments WHERE username = 'ticrane'
然后我想找到分配给我的用户(ticrane)所分配的案例的所有其他用户:
SELECT * FROM assignements WHERE case_id = (all of the case ids generated by the previous query)
我想在一个查询中执行此操作。我想这里的某种联接是有序的,但我认为你不能从同一个表中加入结果。困惑。有什么建议吗?
答案 0 :(得分:4)
将表连接到自身是完全合法的,但是您需要为表的两个“副本”中的至少一个提供别名,以使该语句不含糊。
SELECT
assignments_join.*
FROM
assignments AS assignments_base
JOIN assignments AS assignments_join ON
assignments_base.case_id = assignments_join.case_id
WHERE
assignments_base.username = 'ticrane'
答案 1 :(得分:2)
您需要在作业表
上进行自我加入select a.username, a.case_id
from assignments a inner join assignments b
on a.case_id = b.case_id
where b.username = 'ticrane'
答案 2 :(得分:1)
除了Hammerite和No'am Newman所示的解决方案之外,你还可以使用一个子选择:
SELECT *
FROM assignements
WHERE case_id IN (SELECT case_id from assignments WHERE username = 'ticrane')