我有一个复杂的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
答案 0 :(得分:1)
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
答案 1 :(得分: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
答案 2 :(得分: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>);
您对数据结构的描述有点令人困惑。但我猜测opinion
具有作者和陈述的关键关系(并且statement
没有与之关联的单独用户ID)。
答案 3 :(得分: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