1

我有这个查询。

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 |
+----+
4

2 回答 2

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 演示

基本上,我曾经INNER JOIN只显示channels表中至少有记录的gigs表中的 id。如果即使gigs表上没有匹配项也要显示列表,那么您应该使用LEFT JOIN

于 2012-10-21T23:46:45.343 回答
-2
SELECT id, (SELECT id FROM Gigs WHERE channel_id = c.id ORDER BY id DESC LIMIT 1) As GigID

FROM channels c
于 2012-10-22T00:11:34.970 回答