简体   繁体   中英

Finding matching records from two tables MySQL

I have two tables book1 and book2. I have issue_date column in both the tables. I want to get the records from both tables for matching issue date.

book1 and book2 have the following columns -

book_id | user_id | numofbooks | issue_date

I tried this SQL query given below but doesn't work -

SELECT * FROM `book1`, `book2` WHERE issue_date between '2014-04-06' and '2014-05-07';

Throws an error. Is it possible to do it SQL way or should i query both the tables separately and merge the result sets?

Your question is a bit vague on what you actually want to do. I doubt that you really want a cartesian product of all matching records from the two tables.

I think you want something like this:

SELECT *
FROM book1
WHERE issue_date between '2014-04-06' and '2014-05-07'
UNION ALL
SELECT *
FROM book2
WHERE issue_date between '2014-04-06' and '2014-05-07';

This assumes that the two tables have exactly the same columns defined in the same order (and that, in turn, would suggest a bad database design). In practice, you would replace the * with the columns you really want.

Use UNION ALL :

SELECT * FROM book1
WHERE issue_date between '2014-04-06' and '2014-05-07'
UNION ALL
SELECT * FROM book2
WHERE issue_date between '2014-04-06' and '2014-05-07';

This will only work if book1 and book2 have the same columns in the same order, in which case it's questionable why this wasn't designed as 1 table in the first place.

If the columns don't match exactly you can replace * with the relevant column names.

您可以如上所述应用Union All功能,但是在book1和book2表中的字段名称相同

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