我尝试了UNION,但它没有工作,它说#1221 - UNION和ORDER BY的使用不正确。
SELECT members.Name, friends.MemberNumber1
FROM friends
INNER JOIN members ON friends.MemberNumber1= members.MemNo
WHERE friends.MemberNumber2 LIKE 1
ORDER BY members.Name
UNION
SELECT members.Name, friends.MemberNumber2
FROM friends
INNER JOIN members ON friends.MemberNumber2= members.MemNo
WHERE friends.MemberNumber1 LIKE 1
ORDER BY members.Name
这两个查询都可以自行运行,但我试图将它们放在一个查询中,因为我想对每个查询进行查询。之后在JSTL中的结果集。我也尝试为friends.MemberNumber1和friends.MemberNumber2创建一个别名,但它没有改变任何东西。也许还有一个更简单的查询,我只是没有看到。或者我绝对需要进行两次查询?
由于
答案 0 :(得分:1)
您需要将UNION
放入子查询中,然后对整个事物进行排序。
SELECT *
FROM (
SELECT members.Name, friends.MemberNumber1
FROM friends
INNER JOIN members ON friends.MemberNumber1= members.MemNo
WHERE friends.MemberNumber2 LIKE 1
UNION
SELECT members.Name, friends.MemberNumber2
FROM friends
INNER JOIN members ON friends.MemberNumber2= members.MemNo
WHERE friends.MemberNumber1 LIKE 1) AS u
ORDER BY u.Name
答案 1 :(得分:1)
(SELECT members.Name, friends.MemberNumber1
FROM friends
INNER JOIN members ON friends.MemberNumber1= members.MemNo
WHERE friends.MemberNumber2 LIKE 1)
UNION
(SELECT members.Name, friends.MemberNumber2
FROM friends
INNER JOIN members ON friends.MemberNumber2= members.MemNo
WHERE friends.MemberNumber1 LIKE 1)
ORDER BY members.Name
答案 2 :(得分:1)
您可以执行派生表,然后按顺序排序。 列名必须匹配。 我知道这个答案很接近Barmar,但第二列的aliasName很重要。 你也可以查看UNION和UNION ALL之间的区别,我通常使用后者。
SELECT Name , MemberNumber
FROM (
SELECT members.Name, friends.MemberNumber1 as MemberNumber
FROM friends
INNER JOIN members ON friends.MemberNumber1= members.MemNo
WHERE friends.MemberNumber2 LIKE 1
UNION ALL
SELECT members.Name, friends.MemberNumber2 as MemberNumber
FROM friends
INNER JOIN members ON friends.MemberNumber2= members.MemNo
WHERE friends.MemberNumber1 LIKE 1) AS derived1
ORDER BY derived1.Name
答案 3 :(得分:0)
它还满足您的查询逻辑?
SELECT members.Name, friends.MemberNumber1
FROM friends
INNER JOIN members ON friends.MemberNumber1= members.MemNo
WHERE friends.MemberNumber2 LIKE 1 OR friends.[primarykey] IN (
SELECT friend.[primarykey]
FROM friends
INNER JOIN members ON friends.MemberNumber2= members.MemNo
WHERE friends.MemberNumber1 LIKE 1
)
答案 4 :(得分:0)
试试这个:
SELECT
*
FROM
(
SELECT
Name = members.Name,
MemberNumber = friends.MemberNumber1
FROM
friends
INNER JOIN
members
ON friends.MemberNumber1= members.MemNo
WHERE
friends.MemberNumber2 LIKE 1
UNION ALL
SELECT
Name = members.Name,
MemberNumber = friends.MemberNumber2
FROM
friends
INNER JOIN
members ON friends.MemberNumber2= members.MemNo
WHERE
friends.MemberNumber1 LIKE 1
) Unioned
ORDER BY
Unioned.Name
如果UNION ALL
出现问题,请尝试UNION