mysql:连接结构中的顺序子句写在哪里?
假设我有三个表 - list
、a
和 b
table list
|a_id|--|b_id|--'name'
|4 |--|3 |--|foo|
|1 |--|2 |--|foo|
table a
|id|--|name|--|order|
|1 |--|a_1 |--|1 |
|2 |--|a_2 |--|2 |
.....................
|n |--|a_n |--|n |
table b
|id|--|name|--|order|
|1 |--|b_1 |--|1 |
|2 |--|b_2 |--|2 |
.....................
|n |--|b_n |--|n |
a_id
表 list
> 是来自 a
表的 id,
表 list
中的 b_id
是来自 b
表的 id
我需要获取a
和 b
表中的名称列表按其顺序排序,其中 list
表中的 name
= 'foo'。
IE。我需要从表 a
和 b_2
、b_3
中获取 a_1
、a_4
来自b
。
我编写了一个类似的查询,
SELECT
`a_1_table`.`name` a_1_name,
`b_1_table`.`name` b_1_name
FROM
`list`
LEFT JOIN
`a_1` AS a_1_table ON ( `a_1_table`.`id` = `list`.`a_id` )
LEFT JOIN
`b_1` AS b_1_table ON ( `b_1_table`.`id` = `list`.`b_id` )
WHERE
`list`.`name` = 'foo'
但正如我所见,在这种结构中,我无法编写 order by ...
。 IE。我可以,但我不会得到我想要的。
我能做些什么?
Let's assume I have three table - list
,a
and b
table list
|a_id|--|b_id|--'name'
|4 |--|3 |--|foo|
|1 |--|2 |--|foo|
table a
|id|--|name|--|order|
|1 |--|a_1 |--|1 |
|2 |--|a_2 |--|2 |
.....................
|n |--|a_n |--|n |
table b
|id|--|name|--|order|
|1 |--|b_1 |--|1 |
|2 |--|b_2 |--|2 |
.....................
|n |--|b_n |--|n |
a_id
in table list
is id from a
table, and
b_id
in table list
is id from b
table
I need to get the name list from a
and b
tables ordered by their order, where name
= 'foo' in list
table.
ie. i need to get a_1
,a_4
from table a
, and b_2
,b_3
from b
.
I wrote a query like
SELECT
`a_1_table`.`name` a_1_name,
`b_1_table`.`name` b_1_name
FROM
`list`
LEFT JOIN
`a_1` AS a_1_table ON ( `a_1_table`.`id` = `list`.`a_id` )
LEFT JOIN
`b_1` AS b_1_table ON ( `b_1_table`.`id` = `list`.`b_id` )
WHERE
`list`.`name` = 'foo'
but as I see, in such structure, I can't write order by ...
. ie. I can' but I will not get what I want.
What can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用:
UNION ALL
比UNION
更快,因为它不会删除重复项(UNION
会删除重复项)。Use:
UNION ALL
is faster thanUNION
, because it doesn't remove duplicates (whichUNION
does).