0

我有一个复杂的 INNER JOIN SQL 请求,我无法理解。我希望有人能帮助我。它涉及 3 个表,因此它有 2 个内部连接。

我的数据库有“用户”、“声明”、“意见”表。

用户可以发表声明和意见。意见有一个“authorid”变量引用他们所代表的用户的 id,并且他们有一个“statementid”变量引用他们所引用的语句。

我正在尝试提交一个请求,在给定 2 个陈述的情况下,我可以返回对这两个陈述发表意见的用户列表。

我在想类似的东西

$sid1=5;
$sid2=6;
$sql = "
        SELECT user.*
        FROM users
        INNER JOIN opinion
        ON opinion.authorid=user.uid 
        WHERE opinion.statementid=  [sid1?  how can i use both]
        INNER JOIN statement
        ON statment.uid=opinion.statementid
        ";

但正如你所见,我被困住了。我需要一个 UNION 吗?如果您需要进一步说明,请告诉我。

提前致谢。

编辑:我想出了如何做到这一点:

SELECT DISTINCT users.uid
FROM users
JOIN opinion o, opinion o2
WHERE users.uid = o.authorid
AND users.uid = o2.authorid
AND o2.statementid = $sid2
AND o.statementid = $sid1
4

4 回答 4

2
  SELECT DISTINCT user.*
  FROM opinion o 
  JOIN usrs u 
       ON u.uid = o.author_id
      AND o.statement_id = $sid1
  INTERSECT
  SELECT DISTINCT user.*
  FROM opinion o 
  JOIN usrs u 
       ON u.uid = o.author_id
      AND o.statement_id = $sid2

您的 SQL 方言中没有可用的 INTERSECT?

SELECT A.* FROM (
  SELECT DISTINCT user.*
  FROM opinion o 
  JOIN usrs u 
       ON u.uid = o.author_id
      AND o.statement_id = $sid1
) A
JOIN (
  SELECT DISTINCT user.*
  FROM opinion o 
  JOIN usrs u 
       ON u.uid = o.author_id
      AND o.statement_id = $sid2
) B on A.uid = B.uid
于 2013-07-06T00:29:59.717 回答
0

你应该能够链接它两次。

SELECT user.*
FROM users u. opinion o1, statement s1
     , opinion o2, statement s2 
WHERE o1.authorid=user.uid 
AND o2.authorid = user.uid
AND o1.statement_id = s1.sid
AND o2.statementid = s2.sid
AND s1.sid = $sid1
AND s2.sid = $sid2
于 2013-07-06T00:29:30.030 回答
0

我认为这是您想要的查询:

   SELECT u.*
   from opinion o join
        users u
        on o.authorid = u.uid join
        statement s
        on o.statementid = s.sid
   where s.sid in (<list of statement ids>);

您对数据结构的描述有点混乱。但我猜opinions 拥有作者和陈述是关键关系(并且statement没有与之关联的单独用户 ID)。

于 2013-07-06T00:42:53.030 回答
0
SELECT DISTINCT users.uid
FROM users
JOIN opinion o, opinion o2
WHERE users.uid = o.authorid
AND users.uid = o2.authorid
AND o2.statementid = $sid2
AND o.statementid = $sid1
于 2013-07-09T21:42:42.373 回答