【问题标题】:Getting data from more than 2 mysql tables with join.通过连接从 2 个以上的 mysql 表中获取数据。
【发布时间】:2014-02-27 05:41:50
【问题描述】:

这是我的表格结构。

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。

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

【问题讨论】:

    标签: php mysql sql codeigniter join


    【解决方案1】:
    select * from table1 where id not in (
        select question_id from table3 where reader_id = [particular user id]
    )
    

    【讨论】:

    • 感谢 Loic 的快速回复,我们还需要来自 Table2 的电子邮件,因为 Table2 保存了发布问题和阅读的人的信息。
    • 最好的方法是再提出第二个请求:select email from table2 where id = [particular user id]
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      试试这个:

      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;
      

      【讨论】:

        猜你喜欢
        • 2021-10-16
        • 2018-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-29
        • 1970-01-01
        • 2019-02-27
        • 2014-01-23
        相关资源
        最近更新 更多