[英]MySql using inner join along with union distinct
How to I add a inner join to the following union distinct query?如何将内部联接添加到以下联合不同查询?
select cn_to from connections a where cn_from = '111'
union distinct
select cn_from from connections b where cn_to = '111'
inner join names on connections.cn_to = names.id
The tables are names
and connections
.这些表是
names
和connections
。 The first query works fine.第一个查询工作正常。 Things fail at the
inner join
part.事情在
inner join
部分失败了。 Can you please help?你能帮忙吗?
Table creates and inserts are here http://sqlfiddle.com/#!9/ca27bf/1表创建和插入在这里http://sqlfiddle.com/#!9/ca27bf/1
I'm trying to get results like this我试图得到这样的结果
Name 2
Name 3
Name 4
Name 5
Name 6
Name 7
Name Odd
The correct syntax would be:正确的语法是:
select c.cn_to
from connections c
where c.cn_from = '111'
union distinct
select c.cn_from
from connections c join
names n
on c.cn_to = n.id
where c.cn_to = '111';
WHERE
and FROM
are clauses in the SELECT
statement. WHERE
和FROM
是SELECT
语句中的子句。 JOIN
is an operation only understood in the FROM
clause . JOIN
是一种只能在FROM
子句中理解的操作。 So your clauses are misplaced.所以你的条款放错了地方。
This assumes that your database supports union distinct
.这假设您的数据库支持
union distinct
。
You need to write the UNION
query as a derived table and then JOIN
that to the names
table:您需要将
UNION
查询编写为派生表,然后将其JOIN
到names
表中:
SELECT cn, names.name
FROM (select cn_to AS cn from connections a where cn_from = '111'
union distinct
select cn_from from connections b where cn_to = '111') c
join names on c.cn = names.id
Output: Output:
cn name
222 Name 2
333 Name 3
444 Name 4
555 Name 5
666 Name 6
777 Name 7
121 Name Odd
what you want to select cn_to or name??你想要什么 select cn_to 或名称? if you want names for cn_from = '111' or cn_to = '111':
select names.name from connections inner join names on connections.cn_to = names.id where cn_from = '111' or cn_to = '111';
如果您想要 cn_from = '111' 或 cn_to = '111' 的名称: select names.name from connections 内部连接名称 connections.cn_to = names.id where cn_from = '111' or cn_to = '111';
result: name Name 2 Name 3 Name 4 Name 5 Name 1 Name 1 Name 1 Name 1 link: http://sqlfiddle.com/#!9/ca27bf/13结果:名称名称2名称3名称4名称5名称1名称1名称1名称1链接: http://sqlfiddle.com/#!9/ca27bf/13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.