使用mySQL查询仅获取第一行

时间:2017-02-19 14:25:26

标签: php mysql database join left-join

我有两张桌子

故事

id  |  Story Name   | User id
----+---------------+-----------
2   |  Name         |  12
3   |  Name         |  13
4   |  Name         |  12
5   |  Name         |  12
--------------------------------

线

id  |  Story Line   | story_id |  started_date
----+---------------+----------+------------------------
2   |  Name         |  2       |  2017-02-17 18:20:14
3   |  Name         |  2       |  2017-02-18 18:20:14
4   |  Name         |  3       |  2017-02-18 18:20:14
5   |  Name         |  2       |  2017-02-19 18:20:14
----------------------------------------------------------

我需要从lines表(begin_date的ASC)和故事表中获取第一行

SELECT story.* from stories as story WHERE story.id=2

使用左连接

SELECT story.* 
from stories as story 
LEFT JOIN lines as line 
ON lines.story_id=story.id
WHERE story.id=2

这里如何从行表中获取第一个条目?

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以尝试在此处使用ORDER BYLIMIT结合使用。在这种情况下,我们希望从started_date表中按lines命令升序(MySQL中的默认顺序),同时只保留一条记录,与您定义的第一条记录相对应。

SELECT story.*, line.*
FROM stories AS story 
LEFT JOIN lines AS line 
    ON lines.story_id = story.id
WHERE story.id=2
ORDER BY lines.started_date
LIMIT 1

如果您想获得所有故事的最早记录,则必须使用子查询:

SELECT s.*, l1.*
FROM stories AS s
LEFT JOIN lines l1
    ON s.story_id = l1.story_id
INNER JOIN
(
    SELECT story_id, MIN(started_date) AS first_date
    FROM lines
    GROUP BY story_id
) AS l2
    ON l1.story_id     = l2.story_id AND
       l1.started_date = l2.first_date

答案 1 :(得分:0)

试试这个

SELECT story.* 
from stories as s
LEFT JOIN lines as l
ON lines.story_id=story.id
WHERE story.id=2
ORDER BY s.started_date ASC
LIMIT 1