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 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件