1
我有2個表文章和意見,
每個崗位都有ID,標題,CATEGORY_ID和USER_ID 每個評論有ID,評論,POST_ID和USER_ID如何在主表濾波器左連接查詢
我要列出具有所有帖子CATEGORY_ID = 2和comment.user_id = 1
CREATE TABLE post
(`ID` int, `TITLE` varchar(9), `CATEGORY_ID` int, `USER_ID` int)
;
INSERT INTO post
(`ID`, `TITLE`, `CATEGORY_ID`, `USER_ID`)
VALUES
(1, 'My post A', 1, 1),
(2, 'My post B', 2, 1),
(3, 'My post C', 2, 2)
;
CREATE TABLE comment
(`ID` int, `COMMENT` varchar(12), `POST_ID` int, `USER_ID` int)
;
INSERT INTO comment
(`ID`, `COMMENT`, `POST_ID`, `USER_ID`)
VALUES
(1, 'My comment X', 1, 1),
(2, 'My comment Y', 2, 1),
(3, 'My comment Z', 1, 2)
;
該命令獲取的所有帖子包括一個與CATEGORY_ID = 1
SELECT post.*, comment.comment, comment.post_id, comment.user_id c_user_id
FROM post
LEFT JOIN COMMENT
ON POST.id = COMMENT.post_id
AND COMMENT.user_id=1
AND POST.category_id =2
我得到這個
+---------+-----------+-------------+---------+--------------+---------+-----------+
| USER_ID | TITLE | CATEGORY_ID | USER_ID | COMMENT | POST_ID | C_USER_ID |
+---------+-----------+-------------+---------+--------------+---------+-----------+
| 1 | MY POST A | 1 | 1 | null | null | null |
| 2 | MY POST B | 2 | 1 | My Comment Y | 2 | 1 |
| 1 | MY POST C | 2 | 2 | null | null | null |
+---------+-----------+-------------+---------+--------------+---------+-----------+
,我想獲得這個(所有文章與CATEGORY_ID = 2這樣2條記錄,其中出現USER_ID註釋和其他註釋如下空:
+---------+-----------+-------------+---------+--------------+---------+-----------+
| USER_ID | TITLE | CATEGORY_ID | USER_ID | COMMENT | POST_ID | C_USER_ID |
+---------+-----------+-------------+---------+--------------+---------+-----------+
| 2 | MY POST B | 2 | 1 | My Comment Y | 2 | 1 |
| 1 | MY POST C | 2 | 2 | null | null | null |
+---------+-----------+-------------+---------+--------------+---------+-----------+
預先感謝您的幫助
感謝您的解釋,正是我想要的@GordonLinoff – klark