搜索多个mysql表

时间:2013-01-16 22:20:18

标签: php mysql

我目前有这段代码。

            switch($search_topic)
            {
                case 'Title':
                    $stmt = $dbh->prepare("SELECT game_id, title, platform_name, author_name, price
                                            FROM games 
                                            WHERE title 
                                            LIKE :search_term");
                break;

                case 'Platform':
                    $stmt = $dbh->prepare("SELECT game_id, title, platform_name, author_name, price
                                            FROM games 
                                            INNER JOIN platforms ON games.platform_id = author.platform_id
                                            WHERE platform_name LIKE :search_term");
                break;
            }

search_topic变量来自上一个网页上的列表框,标题搜索工作正常,因为它只是搜索一个MySQL表。当我试图搜索多个表时,平台搜索很难实现,如果这样做有意义的话。

游戏桌有一个名为“platform_id”的列,它链接到平台表,其中关键字段链接到它所在的平台。那么我如何从游戏桌中获取“platform_id”,然后将其链接到“平台”,以便我收回“platform_title”,然后用它进行搜索。

架构:http://sqlfiddle.com/#!2/3d3e3/6

2 个答案:

答案 0 :(得分:3)

基于你的小提琴,这里有你的更新:

SELECT g.game_id, g.title, p.platform_name, a.author_name, g.price
FROM games g
INNER JOIN platforms p ON p.platform_id = g.platform_id
INNER JOIN author a ON a.author_id = g.author_id
WHERE g.title LIKE 'Skyrim';

您显然会将WHERE g.title LIKE 'Skyrim';更改为您要过滤的字段。所以平台查询将是:

SELECT g.game_id, g.title, p.platform_name, a.author_name, g.price
FROM games g
INNER JOIN platforms p ON p.platform_id = g.platform_id
INNER JOIN author a ON a.author_id = g.author_id
WHERE p.platform_name LIKE 'Xbox';

我还建议您将CHARSET更改为utf8而不是latin1,假设这反映了您的生产数据库设置。

答案 1 :(得分:2)

SELECT games.game_id, 
games.title, 
games.platform_name, 
games.author_name, 
games.price, 
games.platform_id, 
platforms.platform_id,
platforms.platform_name
FROM games, platforms 
WHERE
games.platform_id = platforms.platform_id
AND
platform.platform_name LIKE %:search_term%