0

我有两张桌子:

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 实现吗?如何?:)

4

4 回答 4

2

规范化您的数据库。使用您当前的设置,这并非不可能,但绝对不推荐。

-edit-
如果必须,您可以使用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
于 2012-07-09T09:21:33.513 回答
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

如果 Second 不能有许多具有相同 first_id 的行,则可以删除 MIN 和 MAX(以及 Group by)。

于 2012-07-09T09:25:27.550 回答
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

在此处查看演示

于 2012-07-09T09:27:07.347 回答
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
于 2012-07-09T09:35:20.987 回答