【发布时间】:2012-04-22 17:57:11
【问题描述】:
这是我的表格和其中包含的数据:
Table: first
+----------+------+
| first_id | data |
+----------+------+
| 1 | 5 |
| 2 | 6 |
| 3 | 7 |
| 4 | 6 |
| 5 | 7 |
| 6 | 5 |
| 7 | 7 |
| 8 | 6 |
| 9 | 5 |
| 10 | 7 |
+----------+------+
Table: second
+-----------+----------+----------+
| second_id | first_id | third_id |
+-----------+----------+----------+
| 1 | 1 | 2 |
| 2 | 2 | 3 |
| 3 | 3 | 4 |
| 4 | 4 | 2 |
| 5 | 5 | 3 |
| 6 | 6 | 4 |
| 7 | 7 | 2 |
| 8 | 8 | 2 |
| 9 | 9 | 4 |
| 10 | 10 | 4 |
+-----------+----------+----------+
我的目的是获取由data 字段排序的third_ids 列表。现在,我为此运行了以下查询。
SELECT
third_id, data
FROM
first f JOIN second s ON ( s.first_id = f.first_id )
ORDER BY
data ASC;
我按预期得到以下结果。
+----------+------+
| third_id | data |
+----------+------+
| 4 | 5 |
| 2 | 5 |
| 4 | 5 |
| 2 | 6 |
| 3 | 6 |
| 2 | 6 |
| 2 | 7 |
| 4 | 7 |
| 4 | 7 |
| 3 | 7 |
+----------+------+
以下查询也按预期工作。
SELECT
third_id
FROM
first f JOIN second s ON ( s.first_id = f.first_id )
ORDER BY
data ASC;
有输出
+----------+
| third_id |
+----------+
| 4 |
| 2 |
| 4 |
| 2 |
| 3 |
| 2 |
| 2 |
| 4 |
| 4 |
| 3 |
+----------+
然后我运行了以下内容。
SELECT DISTINCT
third_id
FROM
first f JOIN second s ON ( s.first_id = f.first_id )
ORDER BY
data ASC;
但是,在这里我得到了一个意想不到的结果:
+----------+
| third_id |
+----------+
| 2 |
| 3 |
| 4 |
+----------+
这里,3 必须在 2 和 4 之后,因为我在 data 字段上订购。我究竟做错了什么?还是我必须采取不同的策略。
注意: 这种情况发生在我的项目中。此处提供的表不属于原始数据库。它是由我创建来解释问题的。原始表包含数千行。 如果您想试验数据,我将插入数据库转储:
--
-- Table structure for table `first`
--
CREATE TABLE IF NOT EXISTS `first` (
`first_id` int(11) NOT NULL AUTO_INCREMENT,
`data` int(11) NOT NULL,
PRIMARY KEY (`first_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
--
-- Dumping data for table `first`
--
INSERT INTO `first` (`first_id`, `data`) VALUES
(1, 5),
(2, 6),
(3, 7),
(4, 6),
(5, 7),
(6, 5),
(7, 7),
(8, 6),
(9, 5),
(10, 7);
--
-- Table structure for table `second`
--
CREATE TABLE IF NOT EXISTS `second` (
`second_id` int(11) NOT NULL AUTO_INCREMENT,
`first_id` int(11) NOT NULL,
`third_id` int(11) NOT NULL,
PRIMARY KEY (`second_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
--
-- Dumping data for table `second`
--
INSERT INTO `second` (`second_id`, `first_id`, `third_id`) VALUES
(1, 1, 2),
(2, 2, 3),
(3, 3, 4),
(4, 4, 2),
(5, 5, 3),
(6, 6, 4),
(7, 7, 2),
(8, 8, 2),
(9, 9, 4),
(10, 10, 4);
【问题讨论】:
-
“但是,我得到了一个意想不到的结果:” - 这并不意外。
-
如果我是 sql,我会拒绝这个
ORDER BY子句,但是mysql是出了名的容忍它。您想通过哪个data订购? -
@MitchWheat 问题的作者没有预料到,所以从这个意义上说是出乎意料的。他按隐藏列排序,并想知道为什么最终查询中没有保留该顺序。
-
澄清一下,您期望 4,2,3,根据数据顺序选择不同的值?这里不是积极的,但我认为不同的选择会根据不同的字段自动对字段进行排序,否则查询的效率会低得多。
-
如果你想要按数据字段排序的 third_ids 列表,为什么还要使用 distinct 呢?为什么你在查询中有那个 JOIN ? JOIN 似乎未使用,因为 first_id 和数据都在第一个表中。