我想显示我关注的人的帖子
我拥有的3张桌子是:
用户:
+---------+------+
| id_user | name | last_logout
+---------+------+
| 1 | A | 22-02-2018 00:00:10
| 2 | B |
| 3 | C |
| 4 | D |
| 5 | E |
+---------+------+
社区:
+-------------+-------------+
| id_follower | id_followed |
+-------------+-------------+
| 1 | 2 |
| 1 | 3 |
| 1 | 5 |
+-------------+-------------+
文章:
+---------+--------------+---------------+
| id_post | id_user_post | post | date
+---------+--------------+---------------+
| 1 | 2 | hi |
| 2 | 3 | hello |
| 3 | 5 | hey you |
| 4 | 4 | come on |
| 5 | 5 | where are you | 22-02-2018 00:01:00
+---------+--------------+---------------+
我正在使用以下代码,但它不会返回任何内容
SELECT u.name AS n
,p.post AS t
FROM community AS c
LEFT JOIN users AS u ON u.id_user = c.id_followed
LEFT JOIN posts AS p ON c.id_followed = p.id_user_post
WHERE u.id_follower = 1
答案 0 :(得分:0)
Users.id_follower
不存在,所以这就是为什么你什么也得不到,实际上你可能会收到错误(无效的列名'id_follower'。)。
请改用Community.id_follower
。我还建议使用更具描述性的列名(如'username'和'comment')
由于回答您特定问题的纯粹原因,我在查询中使用了“n”和“t”。
SELECT u.name as n, p.post as t
FROM Community c
LEFT JOIN Users u ON c.id_followed = u.id_user
LEFT JOIN Posts p ON c.id_followed = p.id_user_post
WHERE c.id_follower = 1
测试:
;WITH USERS AS(
SELECT *
FROM (VALUES (1,'A'),
(2,'B'),
(3,'C'),
(4,'D'),
(5,'E')) U(id_user, name))
, Community AS(
SELECT *
FROM (VALUES (1,2),
(1,3),
(1,5)) C(id_follower, id_followed))
, posts AS(
SELECT *
FROM (VALUES (1,2,'hi'),
(2,3,'hello'),
(3,5,'hey you'),
(4,4,'come on'),
(5,5,'where are you')) P(id_post, id_user_post, post))
SELECT u.name as n, p.post as t
FROM Community c
LEFT JOIN Users u ON c.id_followed = u.id_user
LEFT JOIN Posts p ON c.id_followed = p.id_user_post
WHERE c.id_follower = 1