2014-10-31 75 views
0

我有2個表User_Posts如何從2個不同的表中獲取數據?

CREATE TABLE IF NOT EXISTS `User_Posts` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `user_id` int(12) NOT NULL, 
    `wall_id` int(12) NOT NULL, 
    `text` text COLLATE utf8_bin NOT NULL, 
    `img` varchar(255) COLLATE utf8_bin NOT NULL, 
    `time` date NOT NULL 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=7 ; 

User_Activity

CREATE TABLE IF NOT EXISTS `User_Activity` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `content` varchar(55) COLLATE utf8_bin NOT NULL, 
    `activity_id` int(12) NOT NULL, 
    `activity` varchar(88) COLLATE utf8_bin NOT NULL, 
    `user_id` int(12) NOT NULL, 
    `time` date NOT NULL, 
    `value` varchar(12) COLLATE utf8_bin NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=131 ; 

,我想獲得的所有活動和崗位,其中USER_ID =?

試圖與

$act = $this->app->db->rawQuery("SELECT p.*, a.* 
           FROM User_Posts p 
           JOIN User_Activity a 
           ON a.user_id = ? OR p.user_id = ?", array($id,$id)); 

做我得到的數據是這樣

Array 
(
    [0] => Array 
     (
      [id] => 130 
      [user_id] => 16 
      [wall_id] => 0 
      [text] => 'Text' 
      [img] => 0 
      [time] => 2014-10-31 
      [deleted] => 0 
      [content] => movie 
      [activity_id] => 5 
      [activity] => favorite 
      [value] => 0 
     ) 

    [1] => Array 
     (
      [id] => 130 
      [user_id] => 16 
      [wall_id] => 0 
      [text] => 'Text' 
      [img] => /posts/ceee9b387dcf72bcb19d1c1c73147ef3.jpg 
      [time] => 2014-10-31 
      [deleted] => 0 
      [content] => movie 
      [activity_id] => 5 
      [activity] => favorite 
      [value] => 0 
     ) 

) 

但我需要

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [user_id] => 16 
      [wall_id] => 0 
      [text] => 'Text' 
      [img] => 0 
      [time] => 2014-10-31 
     ) 

    [1] => Array 
     (
      [id] => 2 
      [user_id] => 16 
      [wall_id] => 0 
      [text] => 'Text' 
      [img] => /posts/ceee9b387dcf72bcb19d1c1c73147ef3.jpg 
      [time] => 2014-10-31 
     ) 

     [2] => Array 
     (
      [id] => 130 
      [content] => movie 
      [activity_id] => 5 
      [activity] => favorite 
      [value] => 0 
     ) 

) 

響應與附加活動的職位,但我需要不同每個人的結果

該怎麼辦?

+0

你試圖做的事情是不可能的。查詢返回的所有行必須具有相同的列。 – nvanesch 2014-10-31 14:26:10

回答

0

只是一個小改

$act = $this->app->db->rawQuery("SELECT p.*, a.* 
          FROM User_Posts p, User_Activity a 
          WHERE a.user_id = p.user_id 
          AND p.user_id = ?", array($id)); 
+0

我從User_Posts獲得了與User_Activity中的附加行相同的結果行 – 2014-10-31 14:19:04

0

你不需要JOIN關鍵字。

SELECT * 
FROM User_Posts, User_Activity 
WHERE `User_Activity`.`User_id` = `User_Posts`.`user_id` 
+0

這是一個連接,只有另一種語法。 – nvanesch 2014-10-31 14:24:52

+0

得到相同的,改變了問題,並再次查看我得到 – 2014-10-31 14:26:10

+0

@ nvanesch,是它加入兩個表,但它不使用'JOIN'。糾正我的語法不利於回答這個問題。如果您覺得您可以更清楚地回答問題,請對其進行編輯。 – 2014-10-31 14:30:16

相關問題