繁体   English   中英

如果第一个中没有足够的行,如何从另一个表中选择行? 用SQL

[英]How to select rows from another table if not enough rows in the first? With SQL

我有两张桌子:

表“项目”:

| id | name       | description                              |
| 1  | Michael    | This is a random description blabalbla   | 
| 2  | Tom        | This is another descriptions blablabla   | 

表“moreitems”:

| id | name       | description                              |
| 1  | Michael    | This is a random description blabalbla   | 
| 2  | Mike       | This is another descriptions blablabla   | 
| 3  | Michael    | This is a random description blabalbla   | 
| 4  | Blain      | This is another descriptions blablabla   | 

目前,我正在从第一个表中获取项目,如下所示:

SELECT * FROM items WHERE name = 'Michael' AND CHAR_LENGTH(description) > 10 LIMIT 3

如果尚未达到limit(3),我想在查询中包含第二个表。 我怎么能这样做 - 没有PHP?

尝试:

SELECT * FROM
(SELECT 'items' table_name, i.* 
 FROM items i WHERE name = 'Michael' AND CHAR_LENGTH(description) > 10 
 UNION ALL 
 SELECT 'moreitems' table_name, m.* 
 FROM moreitems m WHERE name = 'Michael' AND CHAR_LENGTH(description) > 10 
 ORDER BY 1,2) v
LIMIT 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM