douchuanhan8384 2016-01-30 14:01
浏览 43
已采纳

MySQL在多个表中选择列

I'm building quiz type of software and I'm pretty much lost when building complex sql queries that select columns from different tables.

There are four tables that I need to get information from.

Tables structure: http://i.imgur.com/px759LY.png

I have this sql query:

$questions = $this->db->get_results("
    SELECT * FROM
    (
        SELECT * from wp_ket_questions ".$where." ORDER BY RAND() LIMIT ".$limit."
    ) t1
    JOIN wp_ket_answers t2 ON t1.id = t2.question_id
", ARRAY_A);

This query selects columns from wp_ket_questions table and answers from wp_ket_answers table. I also use JOIN to get answers that belong to certain question.

The question is: how do I incorporate wp_ket_categories and wp_categories_questions table in this SQL query so that I could get category name that is related to certain question?

wp_ket_categories table store all possible categories that I can append to question and wp_categories_questions table store cat_id and question_id columns, somehow I need to get category name from wp_ket_categories but I'm not sure how to properly join those tables.

I would be really grateful if someone could explain me what I need to change.

  • 写回答

1条回答 默认 最新

  • dongzhimin2231 2016-01-30 15:05
    关注

    cqusing your logic, try this. You need to link each tables

    SELECT * 
    from wp_ket_questions q, wp_ket_answers a ,wp_ket_categories c ,wp_categories_questions cq
    where 
    q.id = a.question_id 
    AND c.id = cq.cat_id 
    AND a.question_id = cq.question_id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错