MySQL中關(guān)于一堆多查詢,是指使用一條SELECT語(yǔ)句從多個(gè)表格中查詢數(shù)據(jù),并且將這些表格聯(lián)合起來(lái)。下面是一些MySQL中一堆多查詢的例子。
--查詢臭名昭著的黑色貓的信息,包括其所有文章 SELECT cats.name, articles.title, articles.content FROM cats INNER JOIN articles ON cats.id = articles.cat_id WHERE cats.name = 'Black Cat'; --查詢所有文章的標(biāo)題、作者和評(píng)論數(shù)量 SELECT articles.title, authors.name, COUNT(comments.id) as 'comment_count' FROM articles INNER JOIN authors ON articles.author_id = authors.id LEFT JOIN comments ON articles.id = comments.article_id GROUP BY articles.id; --查詢所有科目及其對(duì)應(yīng)的學(xué)生數(shù) SELECT subjects.subject_name, COUNT(students.id) as 'student_count' FROM subjects LEFT JOIN student_subject ON subjects.id = student_subject.subject_id LEFT JOIN students ON student_subject.student_id = students.id GROUP BY subjects.id; --查詢所有學(xué)生及其選課的科目數(shù) SELECT students.name, COUNT(subjects.id) as 'subject_count' FROM students LEFT JOIN student_subject ON students.id = student_subject.student_id LEFT JOIN subjects ON student_subject.subject_id = subjects.id GROUP BY students.id;
這些查詢語(yǔ)句中使用了不同的聯(lián)結(jié)方法(INNER JOIN、LEFT JOIN等)以及GROUP BY、COUNT等聚合函數(shù),可以靈活使用來(lái)滿足不同的需求。