如何限制MySQL中的连接?

时间:2015-03-30 13:06:23

标签: mysql sql

我有两张桌子:

新闻(主要表格):

+----+-------------------------------+
| id | title                         |
+----+-------------------------------+
|  2 | The title of the story is...  |
+----+-------------------------------+

news_images (联结表)

+---------+--------------------------------------+----------------------------+
| news_id | image_name                           | date                       |
+---------+--------------------------------------+----------------------------+
|       2 | 57a8cab7c09306ca2bbaf02c413aa3d5.jpg | 2015-03-30 16:10:35.743337 |
+---------+--------------------------------------+----------------------------+
|       2 | da98cab7c09306ca2bbaf02c413ab2a9.jpg | 2015-03-30 16:10:30.120232 |
+---------+--------------------------------------+----------------------------+

我想执行一个查询,该选择将从news中选择所有列,并从news_images获取与news中的ID对应的第一行。

最初,我的查询是:

SELECT * FROM news n, news_images ni WHERE n.id = ni.news_id;

此SQL查询返回news_images表中包含新闻id的所有图像。之后,在浏览Stackoverflow和MySQL文档后,我将查询修改为:

SELECT n.title, ni.news_image FROM news n, news_images WHERE n.id = ni.news_id AND ni.news_id
    IN (SELECT news_id FROM news_images LIMIT 1);

虽然我安装了最新的MySQL,但是出现以下错误:

{ [Error: ER_NOT_SUPPORTED_YET: This version of MySQL doesn't yet support 

'LIMIT & IN/ALL/ANY/SOME subquery']
  code: 'ER_NOT_SUPPORTED_YET',
  errno: 1235,
  sqlState: '42000',
  index: 0 }

还有其他方法可以限制MySQL中的连接吗?谢谢

1 个答案:

答案 0 :(得分:2)

执行LEFT JOIN以获取没有任何图像的文章。使用NOT EXISTS仅查找同一news_id中不存在旧图像的图像。

SELECT n.title, ni.image, news_images.*
FROM news n LEFT JOIN news_images ni ON n.id = ni.news_id
AND not exists (select 1 from news_images ni2
                where ni.news_id = ni2.news_id
                  and n2i.timestamp < ni.timestamp)