嘿这是我的数据库
users table pages table
|user_firstname| |page_firstname |
----------------------------- --------------------------------
| john | | matt |
| james | | quentin |
| harry | | roland |
| oliver | | thomas |
这是我对搜索应用程序的查询
SELECT user_id,
user_firstname,
user_lastname,
user_profile_picture
FROM users
WHERE user_firstname LIKE :user_firstname
OR user_lastname LIKE :user_lastname
适用于用户表。但是我也想从页面列中搜索。例如,当我按下字母M时,它发现了jaMes,但我也想要Matt和thoMas。问题是如果我键入Q它应该只从页面中找到Quentin,如果我键入J它应该只来自用户。 如何在此查询中包含pages表?
更新我尝试了此查询
SELECT user_id,
user_firstname,
user_lastname,
user_profile_picture
FROM users
WHERE user_firstname LIKE :user_firstname
OR user_lastname LIKE :user_lastname
UNION ALL SELECT page_id,
page_firstname,
page_lastname,
page_profile_picture
FROM pages
WHERE page_firstname LIKE :page_firstname
OR page_lastname LIKE :page_lastname
我的结果是这样的:
array (size=4)
'user_id' => int 5
'user_firstname' => string 'Roland' (length=3)
'user_lastname' => string 'lastname' (length=7)
'user_profile_picture' => string '5_1399841223_536fe1c70ea2b_user_profile.jpg' (length=43)
即使roland在PAGES表中,我得到的结果就像在用户表中一样。我想将它们彼此分开
答案 0 :(得分:1)
你可以这样做:
SELECT user_id,
user_firstname,
user_lastname,
user_profile_picture, 'users' as 'type'
FROM users
WHERE user_firstname LIKE :user_firstname
OR user_lastname LIKE :user_lastname
UNION ALL SELECT page_id,
page_firstname,
page_lastname,
page_profile_picture ,'pages' as 'type'
FROM pages
WHERE page_firstname LIKE :page_firstname
OR page_lastname LIKE :page_lastname
答案 1 :(得分:0)
取决于你想要完成的事情 - 如果你想基本上像对待同一张桌子一样对待它们,那么像这样的东西会起作用
SELECT user_id,
user_firstname,
user_lastname,
user_profile_picture
FROM users
WHERE user_firstname LIKE :user_firstname
OR user_lastname LIKE :user_lastname
UNION ALL
SELECT user_id,
user_firstname,
user_lastname,
user_profile_picture
FROM pages
WHERE user_firstname LIKE :user_firstname
OR user_lastname LIKE :user_lastname
答案 2 :(得分:0)
我相信这可能会有效,未经测试。除了http://www.w3schools.com/sql/sql_union.asp中的实验。
SELECT user_id as user_id,
user_firstname as firstname,
user_lastname as lastname,
user_profile_picture as profile_picture
FROM users
WHERE user_firstname LIKE :user_firstname
OR user_lastname LIKE :user_lastname
union
SELECT pages_id as user_id,
pages_firstname as firstname,
pages_lastname as lastname,
pages_profile_picture as profile_picture
FROM pages
WHERE pages_firstname LIKE :user_firstname
OR pages_lastname LIKE :user_lastname