简体   繁体   English

MySQL选择多个表中的列

[英]MySQL select columns in multiple tables

I'm building quiz type of software and I'm pretty much lost when building complex sql queries that select columns from different tables. 我正在构建测验类型的软件,并且在构建从不同表中选择列的复杂SQL查询时,我几乎迷失了。

There are four tables that I need to get information from. 我需要从四个表中获取信息。

Tables structure: http://i.imgur.com/px759LY.png 表格结构: http//i.imgur.com/px759LY.png

I have this sql query: 我有这个SQL查询:

$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. 该查询从wp_ket_questions表中选择列,并从wp_ket_answers表中选择答案。 I also use JOIN to get answers that belong to certain question. 我还使用JOIN获得属于特定问题的答案。

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? 现在的问题是:我该如何将这个SQL查询wp_ket_categorieswp_categories_questions表,以便我能得到这是针对某些问题的类别名称?

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. wp_ket_categories表存储的所有可能的类别,我可以追加质疑和wp_categories_questions表店CAT_ID和question_id列,不知何故,我需要从wp_ket_categories获取类的名字,但我不知道如何正确地加入这些表。

I would be really grateful if someone could explain me what I need to change. 如果有人可以向我解释我需要改变的地方,我将非常感激。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM