table1 - customer_data
c_id(int)
name(varchar)
table2 - account_data
a_id(int)
c_id(int) - >使用customer_data
。c_id
plan_id(int)
table3 - game_data
g_id(int)
sort(int)
a_id(int) - >使用account_data
。a_id
game_name(var)
我使用子查询从account_data中选择game_data。 那样:
SELECT `a_id`,`c_id`,`plan_id`,
(SELECT `game_name` FROM `game_data` WHERE `a_id` = a.`a_id` ORDER BY `sort` ASC LIMIT 1) as main_game
FROM `accoubt_data` AS a WHERE `a_id` > 0 ORDER BY `id` DESC
此sql适用于来自game_data
account_data
但我无法使用它从game_data
customer_data
我该怎么办?
customer_data
+----------------------+
| c_id | name |
+----------------------+
| 1001 | Joe |
| 1002 | John |
| 1003 | David |
+----------------------+
account_data
+-------------------------------------+
| a_id | cid | plan_id |
+-------------------------------------+
| 6015 | 1002 | 34 |
| 6028 | 1003 | 1 |
| 6088 | 1001 | 9 |
+-------------------------------------+
game_data
+--------------------------------------+
| g_id | game_name | a_id |
+--------------------------------------+
| 8011 | GTA5 | 6015 |
| 8023 | WWE2016 | 6028 |
| 8088 | FIFA16 | 6088 |
| 8095 | FIFA17 | 6088 |
| 8086 | FIFA15 | 6088 |
+--------------------------------------+
这是基础选择
我需要从customer_data.c_id
获取此数据 +--------------------------------------+
| c_id | name | frist_game |
+--------------------------------------+
| 1001 | Joe | FIFA15 |
| 1002 | John | GTA5 |
| 1003 | David | WWE2016 |
+--------------------------------------+
c_id> a_id> g_id ORDER BY sort ASC
答案 0 :(得分:1)
尝试加入:
SELECT c.`c_id`,c.name,
(SELECT `game_name` FROM `game_data`
WHERE `a_id` = a.`a_id`
ORDER BY `sort` ASC LIMIT 1) as first_game
FROM `accoubt_data` a
JOIN customer_data c ON(a.c_id = c.c_id)
WHERE a.`a_id` > 0
ORDER BY a.`id` DESC
答案 1 :(得分:0)
试试这个
SELECT cd.c_id,cd.name, first_game
FROM account_data ad
inner join game_data gd ON ad.a_id = gd.a_id order by gd.g_id,ad.a_id as games
inner join customer_data cd on games.c_id = cd.c_id order by cd.c_id
希望这有效。