开发者

MySQL / Searching Two Tables

开发者 https://www.devze.com 2023-04-10 09:58 出处:网络
I have two tables, \'photos\' and \'videos\'. Together they are almost identical, except one column, \'photoID\' in \'photos\' and \'videoID\' in \'videos\'.

I have two tables, 'photos' and 'videos'. Together they are almost identical, except one column, 'photoID' in 'photos' and 'videoID' in 'videos'.

When a user makes a search, I would like the video results to be mixed 开发者_JAVA技巧with the photo results, obviously from the same recordset.

How is it possible to do this using different column names? If it's not, do I change the column names to something like contentID, in both tables, and use a UNION to join them? It's a lot of work changing the columns but will have to if this isn't possible...


You don't have to change the column names in the tables. Just use an alias on the SELECT. I'd go with a UNION ALL (more efficient than UNION as it won't try to eliminate dupes) and add an additional column to identify where the content came from.

SELECT photoID AS contentID, colA, colB, ..., 'photo' AS ContentType
    FROM photos
UNION ALL
SELECT videoID AS contentID, colA, colB, ..., 'video' AS ContentType
    FROM videos


Select * from
(
SELECT VideoID as MediaID, * FROM Videos
UNION
SELECT PhotoID as MediaID, * FROM Photos
) as T
WHERE MediaID = ?


use something similar to

select photoID AS ContentID, col1, col2 FROM PHOTOS WHERE col1 =...
UNION
select videoID AS ContentID, col1, col2 FROM VIDEOS WHERE col1 =...


select column1, column2, NULL videoID, photoID 
from photos
where criteria = 'criteria'

union all

select column1, column2, videoID, NULL photoID 
from videos
where criteria = 'criteria'


If you are looking to make a union without displaying photoID and videoID, you can do it this way:

SELECT column names from Videos 
UNION
SELECT column names from Photos
0

精彩评论

暂无评论...
验证码 换一张
取 消