跨表SQL查询的正确语法是什么?

时间:2008-10-28 18:49:28

标签: mysql sql

现在,我有

SELECT gp_id FROM gp.keywords 
WHERE keyword_id = 15 
AND (SELECT practice_link FROM gp.practices 
     WHERE practice_link IS NOT NULL 
     AND id = gp_id)

这不会提供语法错误,但是对于应该返回行的值,它只返回0行。

我要做的是从gp.keywords获取gp_id,其中关键字table keyword_id列是特定值,而practice_link是practice表对应于我拥有的gp_id,它存储在id中该表的一栏。

4 个答案:

答案 0 :(得分:3)

我甚至不确定它是否是有效的SQL,所以我很惊讶它正在工作:

SELECT gp_id
FROM gp.keywords
WHERE keyword_id = 15
    AND (SELECT practice_link FROM gp.practices WHERE practice_link IS NOT NULL AND id = gp_id)

相反如何:

SELECT kw.gp_id, p.practice_link
FROM gp.keywords AS kw
INNER JOIN gp.practices AS p
    ON p.id = kw.gp_id
WHERE kw.keyword_id = 15

我会像其他示例中那样避开隐式连接。它只会导致后来流泪。

答案 1 :(得分:1)


select k.gp_id 
from gp.keywords as k,
     gp.practices as p
where
keyword_id=15
and practice_link is not null
and p.id=k.gp_id

答案 2 :(得分:0)

SELECT k.gp_id
FROM gp.keywords k, gp.practices p
WHERE 
   p.id = k.gp_id.AND
   k.keyword_id = 15 AND
   p.practice_link is not null

答案 3 :(得分:0)

SELECT g.gp_id, p.practice_link FROM gp.keywords g, gp.practices p 
WHERE
g.keyword_id = 15 AND p.practice_link IS NOT NULL AND p.id = g.gp_id