加入时来自 table 的唯一 ID
Unique id from table while joining
有以下方案:
Table ticket
- **ticketid** int;
- **terr** int;
Table terrlocation
- **terrid** int;
- **terr_desc** int;
因此,执行以下查询后:
SELECT * FROM ticket tck
LEFT JOIN terrlocation ter on tck.terr = ter.terrid
我会得到:
ticketid | terr | terrid | terr_desc
--------------------------------------
01 | 02 | 02 | A
01 | 02 | 02 | B
01 | 02 | 02 | C
但我的任务是检查 terrlocation 中是否有任何与票证相关的记录,例如1,如果不是 0。我可以通过案例实现它,但是,atm 我得到 3 条记录而不是一条。
在我看来,我需要将子查询放在 LEFT JOIN 中,例如
SELECT * FROM ticket tck LEFT JOIN ((SELECT DISTINCT FROM terrid)
terrlocation ter on tck.terr = ter.terrid)
但它不起作用。我怎样才能达到我的目标? M.b。通过 CTE 更好?
当您使用 DISTINCT
时,您必须指定必须区分的列!试试这个:
SELECT tck.*,CASE WHEN t.terrid is null THEN 0 else 1 end as Your_IND
FROM ticket tck
LEFT JOIN (SELECT DISTINCT terrid FROM terrlocation) t
on tck.terr = t.terrid
有以下方案:
Table ticket
- **ticketid** int;
- **terr** int;
Table terrlocation
- **terrid** int;
- **terr_desc** int;
因此,执行以下查询后:
SELECT * FROM ticket tck
LEFT JOIN terrlocation ter on tck.terr = ter.terrid
我会得到:
ticketid | terr | terrid | terr_desc
--------------------------------------
01 | 02 | 02 | A
01 | 02 | 02 | B
01 | 02 | 02 | C
但我的任务是检查 terrlocation 中是否有任何与票证相关的记录,例如1,如果不是 0。我可以通过案例实现它,但是,atm 我得到 3 条记录而不是一条。
在我看来,我需要将子查询放在 LEFT JOIN 中,例如
SELECT * FROM ticket tck LEFT JOIN ((SELECT DISTINCT FROM terrid)
terrlocation ter on tck.terr = ter.terrid)
但它不起作用。我怎样才能达到我的目标? M.b。通过 CTE 更好?
当您使用 DISTINCT
时,您必须指定必须区分的列!试试这个:
SELECT tck.*,CASE WHEN t.terrid is null THEN 0 else 1 end as Your_IND
FROM ticket tck
LEFT JOIN (SELECT DISTINCT terrid FROM terrlocation) t
on tck.terr = t.terrid