情景:
我需要选择20个用户的所有信息,并选择他们教授的所有语言的教师资料。我试图这样做,但似乎mysql只返回一个没有嵌套数组值的值数组,有没有办法做到这一点?
TABLES:
+------------------------------------------+
| users |
+------------------------------------------+
| id | firstname | email |
+------------------------------------------+
| 18 | Tom | jerry@email.com |
+------------------------------------------+
| 30 | Jerry | tom@email.com |
+------------------------------------------+
| 25 | Butch | butch@email.com |
+------------------------------------------+
+------------------------------------+
| teachers |
+------------------------------------+
| id | user_id | trial_lessons |
+------------------------------------+
| 10 | 18 | yes |
+------------------------------------+
| 26 | 30 | no |
+------------------------------------+
| 28 | 25 | no |
+------------------------------------+
+------------------------------------------+
| teacher_languages |
+------------------------------------------+
| id | teacher_id | language_text_id |
+------------------------------------------+
| 16 | 10 | 6 |
+------------------------------------------+
| 40 | 10 | 8 |
+------------------------------------------+
| 16 | 28 | 6 |
+------------------------------------------+
| 16 | 28 | 10 |
+------------------------------------------+
| 16 | 26 | 6 |
+------------------------------------------+
+-------------------+
| languages |
+-------------------+
| id | language |
+-------------------+
| 6 | English |
+-------------------+
| 8 | French |
+-------------------+
| 10 | Spanish |
+-------------------+
我的代码远远
SELECT
users.*,
nationality.country AS country_of_nationality,
residence.country AS country_of_residence,
FROM
users
LEFT JOIN
text_countries AS nationality
ON
users.nationality = nationality.iso_code_2
AND
nationality.language_id = ?
LEFT JOIN
text_countries AS residence
ON
users.residence_country = residence.iso_code_2
AND
residence.language_id = ?
ORDER BY
users.created_at
DESC LIMIT
20
预期成果
[0] =>
[user_id] => 18
[firstname] => 'Tom'
[teacher_id] => 10
[languages] =>
[language] => 'English'
[language] => 'French'
[1] =>
[user_id] => 30
[firstname] => 'Jerry'
[teacher_id] => 26
[languages] =>
[language] => 'English'
[2] =>
[user_id] => 25
[firstname] => 'Butch'
[teacher_id] => 28
[languages] =>
[language] => 'English'
[language] => 'Spanish'
答案 0 :(得分:0)
MySQL不会返回多维记录。每条记录都是1-D。大多数关系dbs都这样做。
您可以使用GROUP_CONCAT
将多个值收集到一列中,具体取决于您需要语言数据的方式:
SELECT stuff, GROUP_CONCAT(l.language) AS languages
FROM users u
JOIN teachers t ON ....
JOIN teacher_languages tl ON ....
JOIN languages l ON ....
GROUP BY u.id
我假设您知道(并且有?)JOIN
s ...您需要额外的JOIN(多个)到teacher_languages
然后另一个JOIN(单个)到{{ 1}}然后使用languages
将多个语言记录收集到1个值中。