简体   繁体   中英

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

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":

| 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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