如何将逻辑放入SQL?

时间:2013-08-19 09:39:12

标签: mysql sql

首先,我很抱歉这样问愚蠢的问题。 我是sql的新手。从互联网上倾斜了基本的东西,但无法弄清楚这一点。

让我想我有一个名为post的表,我存储人们的帖子。表结构就是这样..

Post_id  | poster_id | text
1        | 12        | "hello this is a post"
2        | 15        | "Another post"
3        | 77        | "More counting"

有一个名为“朋友”的表我存储的朋友是谁。表结构就是这样..

user_one  |  user_two
1         |  88
84        |  33
1         |  66

现在我可以使用这样的SQL来发布帖子

SELECT * FROM POST INNER JOIN frnends ON user_one = poster_id WHERE 1

但是这将通过将两个表连接在一起得到一个表,我可以做这样的逻辑吗?

  

SELECT post FROM post WHERE poster_id =(SELECT user_two,user_one FROM friends WHERE user_one = MY_id OR user_two = MY_id

也许MY_id是变量WHERE MY_id = 1

现在要做这种逻辑吗?

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:1)

抱歉,我缺乏评论的声誉。应该改进Gamal的解决方案以防止My_id的帖子返回;

SELECT *
FROM post p
INNER JOIN friends AS f on p.poster_id IN (f.user_one, f.user_two)
WHERE My_id IN (f.user_one, f.user_two)
AND p.poster<>My_id;

或者,如果你确实想要这些帖子,那么

SELECT *
FROM post p
INNER JOIN friends AS f on p.poster_id IN (f.user_one, f.user_two)
WHERE My_id IN (f.user_one, f.user_two)
AND p.poster<>My_id
UNION
SELECT *, My_id AS user_one, NULL AS user_two
FROM post p
WHERE p.poster=My_id;

问题在于,对于My_id所属的每个关系,Gamals建议将按My_id返回每个帖子一次。

答案 1 :(得分:0)

试试这个:

   SELECT * 
    FROM [sample].[dbo].[posts] a inner join [sample].[dbo].[friends1] b on  a.posterId=b.user_one or a.posterId=b.user_two where a.PosterId=12