获得1个值到1列

时间:2018-06-12 09:03:11

标签: mysql sql phpmyadmin

美好的一天。 我需要输出这样的输出,这可能是输出。 My Output

我有我的剧本 myoutput就是这个 my output

SELECT q_type,q_title,qcategory_question 
FROM `survey_question` as sq LEFT JOIN 
          (SELECT id,qid,qcategory_question 
           FROM survey_category_question
          ) scq ON sq.id = scq.qid

提前致谢。

2 个答案:

答案 0 :(得分:0)

您的查询没问题。您应该在应用程序中处理格式。现在,我将提出一个不同的建议,即使用group by将所有类别放在一行:

SELECT sq.q_type, sq.q_title, GROUP_CONCAT(scq.qcategory_question)
FROM survey_question sq LEFT JOIN 
     survey_category_question scq
     ON sq.id = scq.qid
GROUP BY sq.q_type, sq.q_title;

注意:

  • 限定查询中的所有列名称,尤其是当您有多个表引用时。
  • 子查询是不必要的,可能在MySQL中有害(大多数数据库会忽略它,但MySQL可能会实现它)。
  • 生成的类别将以逗号分隔的列表进行输出。

答案 1 :(得分:0)

虽然我不建议您在查询中执行此操作,因为您可以轻松地在PHP中执行此操作,您可以尝试这个..

SET @row_number = 0;
SELECT q_type, CASE 
    WHEN A.mxnum = AA.num
        THEN q_title
    ELSE ' '
    END AS q_title, qcategory_question
FROM (
SELECT q_type, q_title, qcategory_question, (@row_number: = @row_number + 1) 
       AS num FROM `survey_question` AS sq
LEFT JOIN (
    SELECT id, qid, qcategory_question
    FROM survey_category_question
    ) AA
LEFT JOIN (
    SELECT q_title, max(num) AS mxnum
    FROM (
        SELECT q_type, q_title, qcategory_question, (@row_number: = @row_number + 1) AS num
        FROM `survey_question` AS sq
        LEFT JOIN (
            SELECT id, qid, qcategory_question
            FROM survey_category_question
            ) scq
            ON sq.id = scq.qid
        )
    GROUP BY q_title
    ) A
    ON num = mxnum
);

希望这会有所帮助...