选择我自己的想法和朋友的想法

时间:2014-01-12 21:59:23

标签: php mysql

我有三张桌子

members (id, fname, lname,...)
my_connections(id, member_id, connection_id, approved, ...`)
my_thoughts(id, member_id, thought, shared)`

我的查询

$sql = "
        SELECT mc.* , cp.`id` AS cp_id, cp.*,  m.* 
        FROM `my_connections` mc
        LEFT JOIN `my_thoughts` cp ON mc.`connection_id` = cp.`member_id`  
        LEFT JOIN `members` m ON m.`id` = mc.`connection_id` 
        WHERE mc.`member_id` = '".$member_id."'
        AND mc.`approved` = 1
        AND cp.`shared` = 1
        ORDER BY cp.`date_added` DESC
";

我得到了所有关联的想法,我如何包括我的想法。我尝试了另一个join ::member_id = $ member_id的联接,但它将我的想法分配给我的联系。

1 个答案:

答案 0 :(得分:1)

可能有多种方法可以实现这一点,但如何使用两个单独的查询并使用UNION将其结果合并到一个网格中?为此,您的两个查询都必须选择相同的列。

例如,像这样(编辑过):

SET @my_id = 1;

SELECT * FROM (
SELECT m.fname, m.lname, t.thought FROM members m
JOIN thoughts t on t.memberID = m.id
WHERE m.id = @my_id

UNION

SELECT m2.fname, m2.lname, t.thought FROM members m
JOIN connections c on c.memberID =m.ID
JOIN members m2 on m2.ID = c.connectionID
JOIN thoughts t on t.memberID = m2.ID
WHERE m.ID = @my_id

) tmp

ORDER BY tmp.lname ASC;

SQL小提琴:http://sqlfiddle.com/#!2/405b2/17