通过join从两个以上的mysql表中获取数据。

时间:2014-02-27 05:41:51

标签: php mysql sql codeigniter join

这是我的表结构。

Table1  // it has 4 colums,that saves all the question posted by user

id|question|answer|postby|

Table2  //it has 2 colums, that saves all the signed up users

id|username|email|

Table3 //it saves that which question is read by which user.

id|reader_id|question_id| 

注意:reader_id是表2的id。

问题:我们需要找出那些特定用户没有阅读过的问题。

3 个答案:

答案 0 :(得分:1)

select * from table1 where id not in (
    select question_id from table3 where reader_id = [particular user id]
)

答案 1 :(得分:0)

SELECT table FROM table1 where id NOT IN(SELECT question_id FROM table3 where reader_id IN(SELECT id FROM table2 where username ='XXXX'))

答案 2 :(得分:0)

试试这个:

SELECT t1.*
FROM table1 t1
LEFT JOIN
  (SELECT t3.* 
   FROM 
   table2 t2
   JOIN table3 t3 ON t3.reader_id=t2.id
   WHERE t3.reader_id=SOME USER)t ON t.question_id=t1.id
WHERE t3.id IS NULL;