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

时间:2022-02-23 12:58:06

I have two tables:

我有两张桌子:

Table "items":

表“项目”:

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

Table "moreitems":

表“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   | 

Currently, I'm fetching items from the first table like this:

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

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

I would like to include the second table in the query if the limit (3) has not been reached. How can I do that - without php?

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

1 个解决方案

#1


3  

Try:

尝试:

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

#1


3  

Try:

尝试:

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