简体   繁体   English

如何从多个表组合一个记录

[英]How to GROUP one record from multiple tables

I have two tables lesson and subjects. 我有两节课和课程。 It is a one to many ratio as in each lesson can be categorized under 1 or more subjects resulting in something like "Name" subject: math, science, social studies 这是一对多的比例,因为每节课可以分为1个或更多主题,导致类似“名称”主题:数学,科学,社会研究

This would return 3 records: 这将返回3条记录:
Name, math 名字,数学
Name, science 名字,科学
name, social studies 名称,社会研究

This results in my looping through and combining and messes up my search count 这导致我循环并组合并混淆了我的搜索计数
How can I get one record with all three instead? 我怎样才能获得所有三张唱片呢? So my search count is accurate and I don't need extra PHP code to check if name is the same and gather the extra subject? 所以我的搜索计数是准确的,我不需要额外的PHP代码来检查名称是否相同并收集额外的主题?

I've tried basic 我试过基本的

SELECT * FROM lesson INNER JOIN subjects ON subject.id = lesson.subject

But this results in 3 entries 但这导致3个条目

EDIT 编辑
My query is more complicated than I lead on. 我的查询比我领导的要复杂得多。 I have a middle table keeping tracking of the two tables above and their relation 我有一个中间表,跟踪上面的两个表及其关系
This query is for searching. 此查询用于搜索。 Here's what I have. 这就是我所拥有的。

SELECT name, subject        
FROM lesson As l
INNER JOIN lesson_sub As ls
  ON ls.lesson_id = l.id
INNER JOIN subjects As s
  ON s.id = ls.subject_id
WHERE CONCAT(l.name, s.subject) LIKE '%KEYWORD%' AND s.id = SUBJECT_ID

You can use the GROUP_CONCAT() function with your JOIN query: 您可以将GROUP_CONCAT()函数与JOIN查询一起使用:

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

GROUP_CONCAT(expr) GROUP_CONCAT(表达式)

This function returns a string result with the concatenated non-NULL values from a group. 此函数返回字符串结果,其中包含来自组的连接非NULL值。 It returns NULL if there are no non-NULL values. 如果没有非NULL值,则返回NULL。 The full syntax is as follows: 完整语法如下:

GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]] [SEPARATOR str_val]) GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]] [SEPARATOR str_val])

mysql> SELECT student_name, -> GROUP_CONCAT(test_score) -> FROM student -> GROUP BY student_name; mysql> SELECT student_name, - > GROUP_CONCAT(test_score) - > FROM student - > GROUP BY student_name;

Or: 要么:

mysql> SELECT student_name, -> GROUP_CONCAT(DISTINCT test_score -> ORDER BY test_score DESC SEPARATOR ' ') -> FROM student -> GROUP BY student_name; mysql> SELECT student_name, - > GROUP_CONCAT(DISTINCT test_score - > ORDER BY test_score DESC SEPARATOR'') - > FROM student - > GROUP BY student_name;

So: 所以:

SELECT lesson.name, GROUP_CONCAT(subjects.name SEPARATOR ', ')
    FROM lesson JOIN subjects ON (subject.id = lesson.subject)
    GROUP BY lesson.name;

TEST 测试

CREATE TABLE lesson ( name varchar (20), subject integer );
CREATE TABLE subjects ( id integer, name varchar(20) );

INSERT INTO subjects VALUES ( 1, 'Math' ), ( 2, 'Physics' ), ( 3, 'Chemistry' );

INSERT INTO lesson VALUES ( 'Lesson A', 1 );
INSERT INTO lesson VALUES ( 'Lesson A', 2 );
INSERT INTO lesson VALUES ( 'Lesson A', 3 );
INSERT INTO lesson VALUES ( 'Lesson B', 2 );
INSERT INTO lesson VALUES ( 'Lesson B', 3 );
INSERT INTO lesson VALUES ( 'Lesson C', 1 );

SELECT lesson.name, GROUP_CONCAT(subjects.name SEPARATOR ', ')
    FROM lesson JOIN subjects ON (subjects.id = lesson.subject)
    GROUP BY lesson.name;

+----------+--------------------------------------------+
| name     | GROUP_CONCAT(subjects.name SEPARATOR ', ') |
+----------+--------------------------------------------+
| Lesson A | Math, Chemistry, Physics                   |
| Lesson B | Chemistry, Physics                         |
| Lesson C | Math                                       |
+----------+--------------------------------------------+
3 rows in set (0.00 sec)

MORE COMPLICATED TEST (with intermediate table) 更复杂的测试(带中间表)

CREATE TABLE lesson ( id integer, name varchar (20) );
CREATE TABLE subjects ( id integer, name varchar(20) );
CREATE TABLE lesson_sub ( lesson_id integer, subject_id integer );

INSERT INTO subjects VALUES ( 1, 'Math' ), ( 2, 'Physics' ), ( 3, 'Chemistry' );
INSERT INTO lesson VALUES ( 1, 'Lesson A' ), ( 2, 'Lesson B' ), ( 3, 'Lesson C' );

INSERT INTO lesson_sub VALUES (1,1), (1,2),(1,3),(2,2),(2,3),(3,1);

SELECT lesson.name, GROUP_CONCAT(subjects.name SEPARATOR ', ') AS subjects
    FROM lesson_sub JOIN lesson ON ( lesson.id = lesson_sub.lesson_id )
                    JOIN subjects ON (subjects.id = lesson_sub.subject_id)
    WHERE CONCAT(lesson.name, subjects.name) LIKE '%Chem%'
    GROUP BY lesson.name;

SELECT name, subjects FROM (
    SELECT lesson.name, GROUP_CONCAT(subjects.name SEPARATOR ', ') AS subjects
    FROM lesson_sub JOIN lesson ON ( lesson.id = lesson_sub.lesson_id )
                    JOIN subjects ON (subjects.id = lesson_sub.subject_id)
    GROUP BY lesson.name ) AS lesson_clear
    WHERE CONCAT(name, subjects) LIKE '%Chem%';

+----------+--------------------------------------------+
| name     | GROUP_CONCAT(subjects.name SEPARATOR ', ') |
+----------+--------------------------------------------+
| Lesson A | Chemistry                                  |
| Lesson B | Chemistry                                  |
+----------+--------------------------------------------+
2 rows in set (0.00 sec)

+----------+--------------------------+
| name     | subjects                 |
+----------+--------------------------+
| Lesson A | Physics, Math, Chemistry |
| Lesson B | Physics, Chemistry       |
+----------+--------------------------+
2 rows in set (0.00 sec)

Why the inner join, if you just want the subject names? 如果您只想要主题名称,为什么内部联接?

SELECT subject
FROM lesson

Now, if you want subjects that have at least one lesson, then you could simply do 现在,如果您想要至少有一节课的科目,那么您可以这样做

SELECT DISTINCT subject
FROM lesson
INNER JOIN subjects ON subject.id = lesson.subject

It looks like you are hoping for one record per person, that is per name . 看起来你希望每个人有一条记录,就是每个name

Here's a way to do that: 这是一种方法:

      SELECT name, count(*) subject_count
        FROM lesson 
  INNER JOIN subjects ON subject.id = lesson.subject
    GROUP BY name
    ORDER BY name

If you need the subjects shown in the record by name, try this: 如果您需要按名称显示记录中显示的主题,请尝试以下操作:

      SELECT name, 
             count(*) subject_count,
             group_concat(subject) subjects
        FROM lesson 
  INNER JOIN subjects ON subject.id = lesson.subject
    GROUP BY name
    ORDER BY name 

暂无
暂无

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

相关问题 MySQL从多个表中选择一条记录 - MySQL select one record from multiple tables 如何加入多个 SQL 表并使用正确的 GROUP_CONCAT 数据为每个基表记录返回一行? - How do I join with multiple SQL tables and return one row per base table record with the correct GROUP_CONCAT data? mysql:如何从一个表中提取多个表,并在每个表中进行分组,然后合并为一个结果? - mysql: How to extract multiple tables from one and group by in each, then combine to one result? 如何从多个表中查询数据并显示相对于其上次工作日期的每个设备专用的一条记录 - how to query data from multiple tables and display one record specific to each device relative to their last working date 从一个数据库中的多个表中选择最新记录(MYSQL PHP) - selecting the latest record from multiple tables in one database (MYSQL PHP) 一次将一条记录插入表中的多个表 - Inserting one record at a time to multiple tables from a table 来自一个表下多个表的SQL语句组数据 - SQL statement group data from multiple tables under one 从多个表中选择计数并按一个字段分组 - Select count from multiple tables and group by one field 将来自两个表(多列和多行)的数据分组为一行 - Group data from two tables, multiple columns and rows, into one row 在一个mysql查询中从多个表中选择具有联接分组依据的数据 - select data from multiple tables with join group by, in one mysql query
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM