我有两张桌子:
First:
id | title
1 | aaa
2 | bbb
3 | ccc
Second:
id | first_id | one | two | three | four
1 | 1 | 3 | 1 | 4 | 6
2 | 2 | 4 | 4 | 1 | 2
3 | 3 | 1 | 2 | 3 | 4
我希望展示:
id | title | min | max
1 | aaa | 1 | 6
2 | bbb | 1 | 4
3 | ccc | 1 | 4
这可能与SQL有关吗?怎么样? :)
答案 0 :(得分:2)
规范化您的数据库。根据您当前的设置,这并非不可能,但绝对不推荐。
CNC中
如果必须,您可以使用LEAST()和GREATEST()
-edit2 -
SELECT
a.id,
a.title,
LEAST(b.one,b.two,b.three,b.four) min,
GREATEST(b.one,b.two,b.three,b.four) max
FROM first a
INNER JOIN second b ON a.id=b.first_id
答案 1 :(得分:1)
阅读汤姆的答案,这将是最好的。
无论如何,对我感到羞耻:
SELECT f.id, f.title
MIN(LEAST(s.one, s.two, s.three, s.four)) as min,
MAX(GREATEST(s.one, s.two, s.three, s.four)) as max
FROM First f
INNER JOIN Second s on f.id = s.first_id
GROUP BY f.id, f.title
如果第二个不能有多个具有相同first_id的行,则可以删除MIN和MAX(以及分组依据)。
答案 2 :(得分:1)
您可以使用UNION
执行此操作。试试这个:
SELECT a.id, a.title, MIN(b.c) `Min`, MAX(b.c) `Max`
FROM First a INNER JOIN
(
SELECT first_id, `one` c FROM `Second`
UNION
SELECT first_id, `two` c FROM `Second`
UNION
SELECT first_id, `three` c FROM `Second`
UNION
SELECT first_id, `four` c FROM `Second`
) b on a.id = b.First_ID
GROUP BY a.id
<强> SEE DEMO HERE 强>
答案 3 :(得分:1)
select first_id,F.title ,MIN(num) [min],MAX(num) [max] from (
select first_id,[one] [num]from [Second] union all
select first_id,[two] [num]from [Second] union all
select first_id,[three] [num]from [Second] union all
select first_id,[four] [num] from [Second] )[Second]
join [First] F
on Id=first_id
group by first_id,F.title