MySQL WHERE语法缺乏知识

时间:2011-10-12 13:13:35

标签: mysql

这有效:

SELECT 
s.content_id, s.cover, s.orig_price, s.sale_price, s.exp_date, s.distr_id, 
c.title 

    FROM 
        s, 
        c WHERE c.id = s.content_id;

这不是:

SELECT 
s.content_id, s.cover, s.orig_price, s.sale_price, s.exp_date, s.distr_id, 
c.title,
j.featured

    FROM 
        s, 
        c WHERE c.id = s.content_id,
        j WHERE j.contentid = s.content_id;

我做错了什么?它应该是简单的东西,但我只是看不到它。一直在寻找一个两三小时的答案。

4 个答案:

答案 0 :(得分:2)

  FROM s,c,j WHERE c.id = s.content_id AND j.contentid = s.content_id;

答案 1 :(得分:1)

您的隐式联接不正常。所有表必须位于FROM子句中,以逗号分隔。连接关系都在一个WHERE子句中指定。

SELECT 
  s.content_id, s.cover, s.orig_price, s.sale_price, s.exp_date, s.distr_id, 
  c.title,
  j.featured
FROM 
    s, c, j
WHERE 
  c.id = s.content_id,
  AND j.contentid = s.content_id;

但最好使用显式JOIN来代替。这是现代代码的首选语法。

SELECT 
  s.content_id, s.cover, s.orig_price, s.sale_price, s.exp_date, s.distr_id, 
  c.title,
  j.featured
FROM 
  s JOIN c ON c.id = s.content_id
  JOIN j ON j.contentid = s.content_id;

答案 2 :(得分:0)

问题是多个WHERE子句。尝试将结尾更改为:

FROM
    s, c, j
WHERE
    c.id = s.content_id AND j.contentid = s.content_id;

答案 3 :(得分:0)

您正尝试执行隐式连接,如下所示

SELECT 
s.content_id, s.cover, s.orig_price, s.sale_price, s.exp_date, s.distr_id, 
c.title,
j.featured

FROM s, c, j
WHERE c.id = s.content_id,
AND j.contentid = s.content_id;

您将语法与显式连接混淆,这是相同的事情:

SELECT 
s.content_id, s.cover, s.orig_price, s.sale_price, s.exp_date, s.distr_id, 
c.title,
j.featured
FROM s
INNER JOIN c ON c.id = s.content_id
INNER JOIN j ON j.contentid = s.content_id;