SQL SELECT基于3个其他的tasbles值

时间:2018-01-30 02:27:34

标签: mysql sql jointable

一个SQL查询

我正在尝试根据其他表中的参考BookID从Books表中选择书籍。如果可能的话,我想将此作为一个查询。这是我到目前为止所拥有的。

  • SELECT BookID FROM TitleMeta WHERE Title LIKE '%$search%
  • SELECT BookID FROM AuthorMeta WHERE Author LIKE '%$search%';
  • SELECT BookID FROM LocationMeta WHERE Location LIKE '%$search%';

然后从那些结果:

SELECT * FROM Books WHERE BookID=BookID;

如果有人可以帮助我实现这一点作为一个查询,您SELECT * FROM Books WHERE BookID = 来自上述三个查询BookID中的每一个,我将非常感激。

4 个答案:

答案 0 :(得分:2)

我想你想从三张表中获取BookID。您可以使用UNION将这些表合并为BookID表格,然后您可以使用WHERE BookId IN表格。

像这样简单

SELECT * FROM Books WHERE BookID IN
(
    SELECT BookID FROM TitleMeta WHERE Title LIKE '%$search%'
    UNION 
    SELECT BookID FROM AuthorMeta WHERE Author LIKE '%$search%'
    UNION 
    SELECT BookID FROM LocationMeta WHERE Location LIKE '%$search%'
)

三张表是大表

也许你可以尝试一下。

 SELECT Books.* 
 FROM Books,
(
    SELECT BookID FROM TitleMeta WHERE Title LIKE '%$search%'
    UNION 
    SELECT BookID FROM AuthorMeta WHERE Author LIKE '%$search%'
    UNION 
    SELECT BookID FROM LocationMeta WHERE [Location] LIKE '%$search%'
) AS BookGroupID
WHERE 
    BookGroupID.BookID = BookGroupID.BookID

答案 1 :(得分:1)

尝试此代码可能会帮助您

    SELECT * FROM Books 
    WHERE BookID in (SELECT BookID FROM TitleMeta WHERE Title LIKE '%$search%') 
    or BookID in (SELECT BookID FROM AuthorMeta WHERE Author LIKE '%$search%') 
    or bookID in (SELECT BookID FROM LocationMeta WHERE Location LIKE '%$search%')

答案 2 :(得分:1)

我认为这应该更快......

...没有子查询,左连接确保您获得所有结果,而不对数据库设计或完整性做任何假设。

select b.*
    from Books b
    left join TitleMeta t on t.BookId = b.BookId
    left join AuthorMeta a on a.BookId = b.BookId
    left join LocationMeta l on l.BookId = b.BookId
    where t.Title like '%$search%' or a.Author like '%$search%' or l.Location like '%$search%'

这将找到任何书籍,其中[一]搜索字符串可能是标题,可能是作者,或者可能是位置;并返回任何命中。

注意左连接:不需要在3个查找表中的每一个中表示BookId是有效的。

我希望这会有所帮助。

答案 3 :(得分:1)

我对您的表关系做了一些假设,但这应该是在缺乏CTE功能的数据库上执行此操作的最佳方法 -

select * from Books where BookID in (
  SELECT TM.BookID FROM TitleMeta TM
  join AuthorMeta AM on TM.BookID = AM.BookID
  join LocationMeta LM on TM.BookID = LM.BookID
  WHERE Title LIKE '%$search%'
  or author LIKE '%$search%'
  or Location LIKE '%$search%')