2017-03-14 53 views
1

我正在爲我的學校開發一種社交網絡。JSON_CONTAINS跨表格

有數據庫中的兩個表有兩個表:

  • users,其中包含(VARCHAR)username和(JSON)friends哪位包含用戶名的列表,用戶是朋友,和
  • posts,其中包含(varchar)publisher字段。

如何編寫一個查詢,該查詢返回出版商與給定用戶的朋友的所有帖子?

enter image description here

郵政例如:

| id | publisher | originalPublisher | postdate | content                  | likes | 
| 113 | pvaqueiroz | NULL    | 2017-03-13 | {"contentType":"text","content":"DAB \\o\\","attatchments":[]} |  0 | 

用戶例如:

| id | username | password       | email    | fullname  | likes           | friends            | profpic             | 
| 1 | pvaqueiroz | 827ccb0eea8a706c4c34a16891f84e7b | [email protected] | Paulo Queiroz | [31, 30, 0, 63, 68, 85, 89, 91, 92, 109, 114] | ["hacker", "girassol_l", "Dment", "Leel", "Mr Dibre"] | /carlos/posts_res/d11109ac342482457f87611483d661a6.jpeg | 
+0

添加了兩張圖的圖片 –

+0

請僅僅是您的json字段的示例。 – McNets

+1

這不是一個PHP的問題。你嘗試了什麼? –

回答

1

所以正確的解決方案。

創建報表(跳過領域,因爲它們不需要解釋)

CREATE TABLE `users` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, 
    `name` VARCHAR(45) NULL, 
    `email` VARCHAR(45) NULL, 
    `password` VARCHAR(45) NULL, 
    PRIMARY KEY (`id`)); 

CREATE TABLE `posts` (
    `id` INT NOT NULL AUTO_INCREMENT, 
    `post` VARCHAR(45) NULL, 
    `user_id` INT UNSIGNED NULL, 
    PRIMARY KEY (`id`), 
    INDEX `fk_posts_1_idx` (`user_id` ASC), 
    CONSTRAINT `fk_posts_1` 
    FOREIGN KEY (`user_id`) 
    REFERENCES `users` (`id`) 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION); 

CREATE TABLE `friends` (
    `user_id` INT UNSIGNED NULL, 
    `friend_id` INT UNSIGNED NULL, 
    UNIQUE INDEX `user_friend_idx` (`user_id` ASC, `friend_id` ASC), 
    INDEX `fk_friends_f_users_idx` (`friend_id` ASC), 
    CONSTRAINT `fk_friends_u_users` 
    FOREIGN KEY (`user_id`) 
    REFERENCES `users` (`id`) 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION, 
    CONSTRAINT `fk_friends_f_users` 
    FOREIGN KEY (`friend_id`) 
    REFERENCES `users` (`id`) 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION); 

每次添加一個炸到的用戶,你將只是記錄一對IDS的friends

和查詢會是:

-- Selecting user friends 
SELECT * FROM friends f 
JOIN users u ON u.id = f.friend_id 
WHERE f.user_id = 1 -- Id of user you need friends for 

-- Selecting friends posts 
SELECT * FROM friends f 
JOIN posts p ON p.user_id = f.friend_id 
WHERE f.user_id = 1 -- Id of user you need friends' posts for 
+0

謝謝你的回答,它完美的作品。對不起這個愚蠢的問題,我很抱歉,但我擔心朋友桌的大小,我的意思是......一段時間後它會不會爆炸? –

+0

@PauloQueiroz沒有區別。這將是一個小而簡單的表格。在一個好的硬件上高達5千萬到8千萬行,速度沒有區別。在此之前,您將開始解決其他查詢的問題,並且必須開始使用緩存(Memcached,Redis)。以及你可以期待分割,如果你的MySQL版本是5.1+ –

+0

我看到..你會推薦我將ON DELETE NO ACTION改爲ON DELETE CASCADE嗎? –