MySQL:如何查询多个表并仅将LIMIT应用于一个?

时间:2012-07-23 17:13:55

标签: mysql

假设我有一个包含的表和另一个包含子项的表。我想返回与有限数量的项目相关联的子项目的所有。从本质上讲,我想加入这两个问题:

SELECT * FROM subitem

SELECT * FROM item LIMIT 10

其中subitem.item = item.id

我试过了:

SELECT * FROM subitem INNER JOIN item ON subitem.item = item.id LIMIT 10

但是,此查询仅返回10个子项(如您所料)。我想检索所有子项目,同时仅将项目的数量限制为10.我如何实现这一目标?

4 个答案:

答案 0 :(得分:4)

这将为您提供10件物品。但是,您应该添加WHERE子句和ORDER BY子句以获取您要查找的项目。

SELECT * FROM subitem INNER JOIN 
              (SELECT * FROM items LIMIT 10) AS I
              ON subitem.item = I.id 

答案 1 :(得分:3)

尝试以下查询:

select * from item,subitem where id = item and 
  id in (select id from item limit 10)

如果IN中的LIMIT出现问题,请尝试以下查询:

select * from (select id from item limit 10) as i1, subitem where id =item ;

答案 2 :(得分:0)

可能是这样的:

SELECT * FROM subitem WHERE item IN(SELECT id FROM item LIMIT 10);

答案 3 :(得分:-1)

如何在此查询中使用限制

select tbl_thread.id,user_id,name,tbl_User.alert_flag,thread_name,thread_status,(select CAST(count(*) as UNSIGNED) from tbl_message where thread_id=tbl_thread.id AND read_status='0' and msg_from='EU' ) as unread,thread_timestamp,(select CAST(max(id) as UNSIGNED) from tbl_message where thread_id=tbl_thread.id) as max_id from tbl_thread,tbl_User where tbl_User.UserID=user_id ;