子查询仅返回一个值

时间:2012-10-21 23:43:46

标签: mysql sql

我有这个问题。

SELECT 
  d.gid, d.channel_id
FROM channels, (
  SELECT 
      gigs.id as gid, gigs.channel_id
    FROM gigs
    ORDER BY gigs.id DESC
    LIMIT 1
) as d
WHERE d.channel_id = channels.id
LIMIT 10

我希望为每个gid获得一个channels.id,但它只会返回一列。那是为什么?

演出表

+---------+------------+
| id      | channel_id |
+---------+------------+
| 150661  | 6          |
| 745797  | 6          |
| 483996  | 6          |
| 3407209 | 6          |
| 1175022 | 5          |
| 3238459 | 6          |
| 711413  | 5          |
| 524758  | 5          |
| 154764  | 5          |
| 1594779 | 5          |
| 1659091 | 2          |
| 1086768 | 6          |
| 1161320 | 8          |
| 467394  | 5          |
| 2877040 | 8          |
| 2705821 | 6          |
| 1881747 | 5          |
| 901902  | 1          |
| 143322  | 6          |
| 671658  | 1          |
+---------+------------+

频道表

+----+
| id |
+----+
| 1  |
| 2  |
| 3  |
| 4  |
| 5  |
| 6  |
| 7  |
| 8  |
| 9  |
| 10 |
+----+

2 个答案:

答案 0 :(得分:2)

试试这个,

SELECT  a.id, b.max_ID
FROM    channels a
        INNER JOIN
        (
            SELECT channel_ID, MAX(id) max_ID
            FROM gigs
            GROUP BY channel_ID
        ) b ON a.id = b.channel_ID

SQLFiddle Demo

基本上,我使用INNER JOIN仅显示来自channels表的id,该表在gigs表上至少有记录。如果您想显示列表,即使gigs表上没有匹配项,那么您应该使用LEFT JOIN代替。

答案 1 :(得分:-2)

SELECT id, (SELECT id FROM Gigs WHERE channel_id = c.id ORDER BY id DESC LIMIT 1) As GigID

FROM channels c