Mysql

連接中的不同行

  • August 1, 2013

我有兩個 MySQL 表:

╔═══════════════════╗
║ wpss_question_set ║
╠═══════════════════╣
║ id                ║
║ quesset           ║
╚═══════════════════╝

╔════════════════╗
║ wpss_questions ║
╠════════════════╣
║ id             ║
║ question       ║
║ ques_set_id    ║
╚════════════════╝

ques_set_id是外鍵。查詢是:

SELECT
   wpss_quesset.quesset,
   wpss_questions.*
FROM wpss_quesset
JOIN wpss_questions 
   ON wpss_quesset.id = wpss_questions.ques_set_id;

我在ques_set_id和上得到重複的結果quesset。如何從 ‘ques_set_id和中選擇唯一記錄quesset

截屏

如果您想從在多行中具有相同 FK 的其他連接表中選擇唯一記錄,您可以將查詢用作

SELECT
       wpss_quesset.quesset,
       wpss_questions.*
   FROM wpss_quesset
   JOIN wpss_questions 
       ON wpss_quesset.id = wpss_questions.ques_set_id
  GROUP BY wpss_quesset.id

或者,如果您想獲取相關 FK 的所有記錄,您應該使用 group concat 和 group by

例子

SELECT
       wpss_quesset.quesset,
       GROUP_CONCAT( wpss_questions.question)
       wpss_questions.*
   FROM wpss_quesset
   JOIN wpss_questions 
       ON wpss_quesset.id = wpss_questions.ques_set_id
  GROUP BY wpss_quesset.id
SELECT * from (SELECT
       wpss_quesset.quesset,
       GROUP_CONCAT( wpss_questions.question)
       wpss_questions.*
   FROM wpss_quesset
   JOIN wpss_questions 
       ON wpss_quesset.id = wpss_questions.ques_set_id
  GROUP BY wpss_quesset.id order by rand()) abc limit 1

引用自:https://dba.stackexchange.com/questions/47326